问题
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.
- 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 theprintln
statement or removing the no-argument constructor alltogether. Add a second constructor within
B
which does not print anything and call it fromC
:B(boolean b) { }
C() { super(true); }
Make sure
C
does not extendB
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