Ganshyam
Ganshyam

Reputation: 31

how is it call abstract class constructor when i create subclass object?

// how is it call abstract class constructor when i create subclass object ?
abstract class D {
    D() {
        System.out.println("called abstract class D constructor");//print
    }
}
public class DemoAbs extends D {
    DemoAbs() {
        System.out.println("called DemoAbs class constructor");
    }
    // how is it call abstract class constructor when i create subclass object ?
    public static void main(String[] args) {
        DemoAbs d=new DemoAbs();
    }
}

Upvotes: 1

Views: 569

Answers (3)

Nikita Mantri
Nikita Mantri

Reputation: 142

Whenever you create an object of subclass, the constructor of subclass will call superclass constructor using super() implicitly. If your parent class constructor accepts parameters, then it is required explicitly to call super(params...); Otherwise it'll show compilation error.

Upvotes: 0

Azodious
Azodious

Reputation: 13872

It's called constructor chaining:

Very first line in a constructor is super() unless you explicitly call this() OR this(<with args>) OR super(<with args>)

You should go through:

Constructor Chaining in Java

Java Constructor Chaining

Upvotes: 2

Anindya Dutta
Anindya Dutta

Reputation: 1982

Whenever a constructor is called, it first calls super(), which means that the constructor of the superclass is called to initialize all variables in the superclass, after which the rest of the constructor of the subclass is executed.

Upvotes: 0

Related Questions