我为什么要在Java中调用super()? [英] Why should I call super() in Java?

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

问题描述

我在一本关于java的书中看到了一个例子:

I see an example from a book that I read about java:

public class A{
  public A(){
      System.out.println("A");
   }
}

public class B extends A{
    public B(){
       super();
       System.out.println("B");
   }

    public static void main(String[] args){
        B b = new B();
    }
}

我不明白为什么要 super()在这儿?即使我删除 super(),我也会得到相同的结果(A会被打印,然后是B)。据我所知,当我初始化子类时,父类在它之前初始化。那么为什么要使用 super()

I can't understand why should super() be here? Even if I delete super(), I would get the same result (A would be printed, and then B). As I understand, when I initialize the subclass, then the parent class is initialize before it. So why use super()?

推荐答案

在这种特殊情况下,你不需要调用 super(); ,因为Java将隐式地插入对 super(); 的调用在构造函数中,如果您没有显式调用它。 ( Java Tutorial link)

In this particular case, you don't need to call super();, because Java will insert the call to super(); implicitly in a constructor if you don't explicitly call it. (Java Tutorial link).

只有在其他情况下才需要调用超类中的另一个非默认构造函数,例如:

It only becomes necessary in other cases, in which you want to call another, non-default constructor in the superclass, such as this:

public class A{
  public A(String s){
      System.out.println("A");
   }
}

public class B extends A{
    public B(String s){
       super(s);
       System.out.println("B");
   }
}

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

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