Why should I call super() in Java?

后端 未结 5 1132
青春惊慌失措
青春惊慌失措 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 04:59

    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)

    0 讨论(0)
  • 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;
    }
    }
    
    0 讨论(0)
  • 2021-01-22 05:10

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

    0 讨论(0)
  • 2021-01-22 05:12

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

    0 讨论(0)
  • 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");
       }
    }
    
    0 讨论(0)
提交回复
热议问题