How can I name the constructor of the parent class?

As we can call the constructor of a great parent.

for example: Binherits from Aand Cinherits from B.

I need to call the constructor Ain C. Can I create an instance B?

If I need it, how can this be implemented in Java.

+3
source share
5 answers

use super()from C and from B to access the 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 everyone is the default constructor, then there is no need to write super();, it will implicitly call it.

, super(parameter.. )

+3

A C.

( ) ", . B A ( ). C B, A.

+6

C B B ...

+2

:

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)")};
}

:

C c = new C();

: A()B()C(), :

C c = new C(new Object());

: A(Object)B(Object)C(Object).

, super(), .

0

, B, A, A B. , Java: http://download.oracle.com/javase/tutorial/java/IandI/subclasses.html.

:

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

new C() , , A() - B() - C()

0

Source: https://habr.com/ru/post/1779397/


All Articles