Why should I call super() in Java?

后端 未结 5 1135
青春惊慌失措
青春惊慌失措 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条回答
  •  盖世英雄少女心
    2021-01-22 05:06

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

提交回复
热议问题