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

白昼怎懂夜的黑 提交于 2020-01-06 07:55:30

问题


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

回答1:


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:

  • Change the constructor of B so it no longer prints "Constructor B" by either removing the println statement or removing the no-argument constructor alltogether.
  • Add a second constructor within B which does not print anything and call it from C:

    B(boolean b) {
    
    }
    
    C() {
        super(true);
    }
    
  • Make sure C does not extend B anymore:

    class C {
        public C() {
            System.out.println("Constructor C");
        }
    }
    



回答2:


No, you can't do this. Java will call all constructors according the hierarchy.



来源:https://stackoverflow.com/questions/54628164/i-want-to-call-only-child-class-constructor-in-multilevel-inheritance

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!