简体   繁体   中英

Calling an overloaded constructor of superclass in Java

In java, can a contructor in a class call an overloaded constructor of its superclass (say if we wanted to make that call explicitly and deliberately).

I know that a constructor in a class makes implicit call to no-arg default constructor of superclass (with super(); ). But suppose I make a call to an overloaded superclass constructor (say super(String s); ), then my question is, Is this possible? And if this is possible, then is a call to super() still made ahead of super(String s) or not and what are its implications?

Yes, you can call an overloaded constructor of the superclass. And that should be the first statement inside the constructor.

And no, you can only invoke the superclass's constructor once, so a call to super(args) would substitute the implicit call to super() . For the example:

A.java

public class A {
    private String fieldA;

    public A(String a) {
        fieldA = a;
    }
}

B.java

public class B extends A {
    private int fieldB;

    public B(String a, int b) {
        // Call the overloaded constructor of the class A
        super(a); // replaces the implicit call to super()
        fieldB = b;
    }
}

but if you do this, you will get an error because the call to super() is not the first statement of the constructor:

public B(String a, int b) {
    fieldB = b;
    super(a); // Call to super() must be first statement in constructor body
}

Yes, we can override super-class's constructor call, while override super-class's default constructor call it will not skip/avoid to call default constructor call.

Refer this code and kindly see output,

Class A{
  A(){
        System.out.println("A-Default");
  }
  A(String msg){
     System.out.println("A-With one Argument msg : " + msg );
  }
}
public Class B extends A{
    B(){
             super("Hi");  
             System.out.println("B-Default");
    }

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

}

Output : 

A-With one Argument msg : Hi
B-Default

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM