javainheritanceconstructorconstructor-chaining

I want to call only child class constructor in multilevel inheritance?


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

Solution

  • Like the comments and the other answer already said, this is explicitly impossible.

    If a class (class Foo) extends another class (class Bar), then all constructors of Foo must directly or indirectly call one of the constructors of Bar. This is done either through explicit invocation or implicit invocation.

    class Foo {
    
        // No constructor is specified, so a default, empty constructor is generated:
        // Foo() { }
    
    }
    
    class Bar extends Foo {
    
        Bar() {
            // Explicit call to a constructor of the super class is omitted, so a
            // default one (to Foo()) is generated:
            // super();
        }
    
    }
    

    In the Java Language Specification § 12.5 it is written how new instances are created. For any class other than Object the super constructor is always executed.

    1. This constructor does not begin with an explicit constructor invocation of another constructor in the same class (using this). If this constructor is for a class other than Object, then this constructor will begin with an explicit or implicit invocation of a superclass constructor (using super). Evaluate the arguments and process that superclass constructor invocation recursively using these same five steps. If that constructor invocation completes abruptly, then this procedure completes abruptly for the same reason. Otherwise, continue with step 4.

    So a super constructor is always called. If you want to print only "Constructor C", then you need to do any of the following: