Why should I call super() in Java?

自闭症网瘾萝莉.ら 提交于 2019-12-20 03:07:32

问题


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

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()?


回答1:


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



回答2:


super(); is redundant and unneeded. However sometimes you want to or must call a specific super class constructor. In those situations you would need to use it with the appropriate parameters: super( params );




回答3:


Java implicitly calls the no argument super constructor. But it may happen that the super class constructor has arguments or there are multiple super class constructors. In this case you would have to explicitly mention which super class constructor you want to call (the compiler leaves that up to you)




回答4:


The first thing that happens in any constructor is a call to this() or super(); There is no harm putting in empty super(), but if you dont the compiler will generate it.
An explicit call is only necessary when the constructor of the superclass takes parameters.

class Parent{
Parent(String s1){

}
}

class Child extends Parent{
Child(String s1,String s2){
super(s1);
this.s2=s2;
}
}



回答5:


Super is called automatically by java. Unless you overload the constructors. I think this might be right no clue though.



来源:https://stackoverflow.com/questions/22566187/why-should-i-call-super-in-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!