class A {
public A() {
System.out.println("Constructor A");
}
}
class B extends A {
public B() {
System.out.println("Constructor B");
}
}
class C extends B {
public C() {
System.out.println("Constructor C");
}
public static void main(String[] args) {
C c = new C();
}
}
When running the code then it calls all constructor but needs to call only child constructor.
output like only print
Constructor C
Like the comments and the other answer already said, this is explicitly impossible.
If a class (class
Foo) extends another class (classBar), then all constructors ofFoomust directly or indirectly call one of the constructors ofBar. This is done either through explicit invocation or implicit invocation.In the Java Language Specification ยง 12.5 it is written how new instances are created. For any class other than
Objectthe super constructor is always executed.So a
superconstructor is always called. If you want to print only "Constructor C", then you need to do any of the following:Bso it no longer prints "Constructor B" by either removing theprintlnstatement or removing the no-argument constructor alltogether.Add a second constructor within
Bwhich does not print anything and call it fromC:Make sure
Cdoes not extendBanymore: