简体   繁体   中英

How to not call parent constructor

When an instance of an inherited class is created, it runs its parent constructor, too. How can I make my child so it doesn't call my parent constructor?

 class parent {

    int a;

    parent() {
        System.out.println("parent");
    }
}

class child extends parent {

    child() {
        System.out.println("child");
    }

}

public class Test2 {

    public static void main(String args[]) {
        child a = new child();
    }
}

As others have said, this is not possible. If you're in a scenario where you think this is necessary, something is wrong with your design.

That being said, you can get away with something similar by adding another constructor to your parent class and explicitly calling it:

class Parent {

    int a;

    Parent() {
        System.out.println("parent");
    }

    Parent(boolean unused){
       //do nothing
    }
}

class Child extends Parent {

    Child() {
        super(false);
        System.out.println("child");
    }

}

public class Test2 {

    public static void main(String args[]) {
        Child a = new Child();
    }
}

如果不需要使基类的多个实例,则可以将基类的构造函数设为私有。

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