Why should I call super() in Java?

后端 未结 5 1179
青春惊慌失措
青春惊慌失措 2021-01-22 04:17

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          


        
5条回答
  •  萌比男神i
    2021-01-22 05:14

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

提交回复
热议问题