我什么时候使用 super()? [英] When do I use super()?

查看:32
本文介绍了我什么时候使用 super()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在 Java 课程中学习类继承,但我不明白何时使用 super() 调用?

I'm currently learning about class inheritance in my Java course and I don't understand when to use the super() call?


我找到了使用 super.variable 的代码示例:


I found this example of code where super.variable is used:

class A
{
    int k = 10;
}

class Test extends A
{
    public void m() {
        System.out.println(super.k);
    }
}

所以我理解到这里,你必须使用super来访问超类中的k变量.然而,在任何其他情况下,super(); 做了什么?靠自己?

So I understand that here, you must use super to access the k variable in the super-class. However, in any other case, what does super(); do? On its own?

推荐答案

完全调用 super() 总是 多余的.它明确地做否则会隐含地做的事情.这是因为如果您省略对超级构造函数的调用,那么无论如何都会自动调用无参数的超级构造函数.并不是说它的风格不好;有些人喜欢露骨.

Calling exactly super() is always redundant. It's explicitly doing what would be implicitly done otherwise. That's because if you omit a call to the super constructor, the no-argument super constructor will be invoked automatically anyway. Not to say that it's bad style; some people like being explicit.

然而,当超级构造函数接受您想从子类传入的参数时,它变得有用.

However, where it becomes useful is when the super constructor takes arguments that you want to pass in from the subclass.

public class Animal {
   private final String noise;
   protected Animal(String noise) {
      this.noise = noise;
   }

   public void makeNoise() {
      System.out.println(noise);
   }
}

public class Pig extends Animal {
    public Pig() {
       super("Oink");
    }
}

这篇关于我什么时候使用 super()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆