Java 我什么时候使用 super()?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4090834/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 11:31:11  来源:igfitidea点击:

When do I use super()?

javainheritancesuper

提问by muttley91

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

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

Edit:
I found this example of code where super.variableis used:

编辑:
我发现这个代码示例在哪里使用:super.variable

class A
{
    int k = 10;
}

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

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

所以我理解到这里,你必须使用super访问k超类中的变量。但是,在任何其他情况下,有什么作用super();呢?在其自己的?

采纳答案by Mark Peters

Calling exactlysuper()is alwaysredundant. 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.

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

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");
    }
}

回答by AHungerArtist

You could use it to call a superclass's method (such as when you are overriding such a method, super.foo() etc) -- this would allow you to keep that functionality and add on to it with whatever else you have in the overriden method.

您可以使用它来调用超类的方法(例如,当您覆盖这样的方法时,super.foo() 等)——这将允许您保留该功能并使用您在覆盖中的任何其他内容添加到它方法。

回答by Ben Groot

回答by robev

The first line of your subclass' constructor must be a call to super()to ensure that the constructor of the superclass is called.

子类的构造函数的第一行必须调用super()以确保调用超类的构造函数。

回答by Jon

When you want the super class constructor to be called - to initialize the fields within it. Take a look at this article for an understanding of when to use it:

当您希望调用超类构造函数时 - 初始化其中的字段。看看这篇文章以了解何时使用它:

http://download.oracle.com/javase/tutorial/java/IandI/super.html

http://download.oracle.com/javase/tutorial/java/IandI/super.html

回答by TartanLlama

You would use it as the first line of a subclass constructor to call the constructor of its parent class.

您将使用它作为子类构造函数的第一行来调用其父类的构造函数。

For example:

例如:

public class TheSuper{
    public TheSuper(){
        eatCake();
    }
}

public class TheSub extends TheSuper{
    public TheSub(){
        super();
        eatMoreCake();
    }
}

Constructing an instance of TheSubwould call both eatCake()and eatMoreCake()

构造一个 的实例TheSub将同时调用eatCake()eatMoreCake()

回答by 0xCAFEBABE

You call super()to specifically run a constructor of your superclass. Given that a class can have multiple constructors, you can either call a specific constructor using super()or super(param,param)oder you can let Java handle that and call the standard constructor. Remember that classes that follow a class hierarchy follow the "is-a" relationship.

您调用super()以专门运行超类的构造函数。鉴于一个类可以有多个构造函数,您可以使用调用特定的构造函数,super()或者super(param,param)可以让 Java 处理它并调用标准构造函数。请记住,遵循类层次结构的类遵循“is-a”关系。

回答by Zain Shaikh

superis used to call the constructor, methodsand propertiesof parent class.

super用于调用父类的constructor,methodsproperties

回答by Dhiraj Shekar

You may also use the superkeyword in the sub class when you want to invoke a method from the parent class when you have overridden it in the subclass.

super当您在子类中重写父类中的方法时,您也可以在子类中使用关键字。

Example:

例子:

public class CellPhone {
    public void print() {
        System.out.println("I'm a cellphone");
    }
}

public class TouchPhone extends CellPhone {
    @Override
    public void print() {
        super.print();
        System.out.println("I'm a touch screen cellphone");
    }
    public static void main (strings[] args) {
        TouchPhone p = new TouchPhone();
        p.print();
    }
}

Here, the line super.print()invokes the print()method of the superclass CellPhone. The output will be:

在这里,该行super.print()调用print()超类的方法CellPhone。输出将是:

I'm a cellphone
I'm a touch screen cellphone

回答by Ravindra babu

From oracle documentation page:

从 oracle 文档页面

If your method overrides one of its superclass's methods, you can invoke the overridden method through the use of the keyword super.

如果您的方法覆盖了其超类的方法之一,则可以通过使用关键字来调用被覆盖的方法super

You can also use superto refer to a hidden field (although hiding fields is discouraged).

您还可以使用super来引用隐藏字段(尽管不鼓励隐藏字段)。

Use of superin constructor of subclasses:

super在子类的构造函数中使用:

Invocation of a superclass constructor must be the first line in the subclass constructor.

超类构造函数的调用必须在子类构造函数的第一行。

The syntax for calling a superclass constructor is

调用超类构造函数的语法是

super();  

or:

或者:

super(parameter list);

With super(), the superclass no-argument constructor is called. With super(parameter list), the superclass constructor with a matching parameter list is called.

使用super(),调用超类无参数构造函数。使用super(parameter list),调用具有匹配参数列表的超类构造函数。

Note: If a constructor does not explicitly invoke a superclass constructor, the Java compiler automatically inserts a call to the no-argument constructor of the superclass. If the super class does not have a no-argument constructor, you will get a compile-time error.

注意:如果构造函数没有显式调用超类构造函数,Java 编译器会自动插入对超类的无参数构造函数的调用。如果超类没有无参数构造函数,则会出现编译时错误。

Related post:

相关帖子:

Polymorphism vs Overriding vs Overloading

多态 vs 覆盖 vs 重载