简体   繁体   中英

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

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

每当调用构造函数时,它都会先调用super() ,这意味着将调用super()类的构造函数以初始化超类中的所有变量,然后再执行子类的其余构造函数。

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.

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