什么时候使用 super() ?

发布于 2024-10-01 04:30:51 字数 389 浏览 7 评论 0原文

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

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

class A
{
    int k = 10;
}

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

所以我明白,在这里,您必须使用 super 来访问 k 超类中的变量。但是,在任何其他情况下,super(); 会做什么?靠自己吗?

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

Edit:
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);
    }
}

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(11

拿命拼未来 2024-10-08 04:30:51

准确地调用super()总是是多余的。它显式地执行否则隐式执行的操作。这是因为,如果您省略对超级构造函数的调用,则无论如何都会自动调用无参超级构造函数。并不是说这种风格不好;而是说这种风格不好。有些人喜欢直白。

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

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

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");
    }
}
夏尔 2024-10-08 04:30:51

super用于调用父类的构造函数方法属性

super is used to call the constructor, methods and properties of parent class.

千秋岁 2024-10-08 04:30:51

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

示例:

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

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

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

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

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:

I'm a cellphone
I'm a touch screen cellphone
赠意 2024-10-08 04:30:51

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

例如:

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

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

构造 TheSub 实例将调用 eatCake()eatMoreCake()

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 TheSub would call both eatCake() and eatMoreCake()

风柔一江水 2024-10-08 04:30:51

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

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

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

世界和平 2024-10-08 04:30:51

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

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.

一曲爱恨情仇 2024-10-08 04:30:51

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

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.

緦唸λ蓇 2024-10-08 04:30:51

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

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

ι不睡觉的鱼゛ 2024-10-08 04:30:51

我刚刚尝试过,评论 super();正如 @Mark Peters 所说,做了同样的事情,但没有评论

package javaapplication6;

/**
 *
 * @author sborusu
 */
public class Super_Test {
    Super_Test(){
        System.out.println("This is super class, no object is created");
    }
}
class Super_sub extends Super_Test{
    Super_sub(){
       super();
       System.out.println("This is sub class, object is created");
    }
    public static void main(String args[]){
        new Super_sub();
    }
}

I just tried it, commenting super(); does the same thing without commenting it as @Mark Peters said

package javaapplication6;

/**
 *
 * @author sborusu
 */
public class Super_Test {
    Super_Test(){
        System.out.println("This is super class, no object is created");
    }
}
class Super_sub extends Super_Test{
    Super_sub(){
       super();
       System.out.println("This is sub class, object is created");
    }
    public static void main(String args[]){
        new Super_sub();
    }
}
平定天下 2024-10-08 04:30:51

来自 Oracle 文档 页面

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

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

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

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

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

super();  

or:

super(parameter list);

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

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

相关文章:

多态性与覆盖与重载

From oracle documentation page:

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

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

Use of super in constructor of subclasses:

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.

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.

Related post:

Polymorphism vs Overriding vs Overloading

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文