简体   繁体   中英

How can I call the constructor of the grand parent class?

How can we call the constructor of grand parent.

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必须调用B的构造函数,然后B将调用A的构造函数...没有其他选项可以调用Grand parent的构造函数

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM