How can we call the constructor of grand paren开发者_JAVA技巧t.
eg: B
inherits from A
and C
inherits from B
.
I need to call the constructor of A
in C
. Is it possible without creating an instance of B
?
If i need this how this can be implemented in Java.
You can't invoke the constructor of A
directly in the constructor of C
.
You can (and actually must) call it indirectly, 'though. Each constructor of B
has to call a constructor of A
(either explicitly or implicitly). Since every constructor of C
needs to call one of the constructors of B
you will always call one of A
s constructors.
use super()
from C and from B to access A's constructor
class A {
public A() {
System.out.println("A");
}
}
class B extends A {
public B() {
super();
System.out.println("B");
}
}
class C extends B {
public C() {
super();
System.out.println("C");
}
}
public class Inheritance {
public static void main(String[] args) {
C c = new C();
}
}
Output :
A
B
C
Note:
If all are default constructor then no need to write super();
it will implicitly call it.
If there is parametrized constructor then super(parameter.. )
is needed
C will have to call B's constructor and in turn B will call A's constructor... there is No other option to call Grand parent's constructor
An example to Joachim's answer:
class A {
A() { System.out.print("A()")};
A(Object o) { System.out.print("A(Object)")};
}
class B {
B() { super(); System.out.print("B()")};
B(Object o) { super(o); System.out.print("B(Object)")};
}
class C {
C() { super(); System.out.print("C()")};
C(Object o) { super(o); System.out.print("C(Object)")};
}
Now calling:
C c = new C();
will produce: A()B()C()
, while calling:
C c = new C(new Object());
will produce: A(Object)B(Object)C(Object)
.
As you can see, by manipulating super()
call you can actually call explicit parent constructor.
Actually, if you have class B extending class A, you can't avoid to call the constructor method for A when you create an instance of the class B. If this mechanism doesn't seems clear to you, I recommend this reading about Java's inheritance system: http://download.oracle.com/javase/tutorial/java/IandI/subclasses.html .
Here's an example:
class A {
public A() {
doSomethingA();
}
}
class B extends A {
public B() {
super(); // this is the call to the A constructor method
doSomethingB();
}
}
class C extends B {
public C() {
super(); // this is the call to the B constructor method
doSomethingC();
}
}
Creating a new object with new C()
will involve, in order, the calling of A() - B() - C()
精彩评论