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

查看:134
本文介绍了我什么时候使用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天全站免登陆