简体   繁体   中英

Instance of child in parent class

I have class In java: A . And class B which extends class A .

Class A hold instance of class B .

I notice that when I call the constructor of class B (when I init this parameter in class A), It does super(), create a new instance of A and init all it fields.

How I can tell class B that the concrete instance of class A (which init it field) - it his parent class?

Your question is really hard to understand, but I guess the problem is this this (your approach):

public class A {
    public B b = new B();
}

public class B extends A {
}

So, when you run new A() you get a StackOverflowError .

In my practical experience, I never needed a design like that, and I'd strongly recommend to re-think your approach. However, if it is really needed, you could use a dedicated init() method, eg:

public class A {
    public B b;

    public void init() {
        b = new B();
    }
}


A a = new A();
a.init();

If you needed A within B you could just do it with a custom constructor for B:

class B extends A {

    A a;     

    public B() {
        super();
        this.a = this;
    }
}

This case is harder though so you need:

class A {
    B b;     
}

class B extends A {
     public B() {
         super();
         b = this;
     }
}

Note that you should not pass the B into the call to super() as B will not be initialized, you should do it as the last step in the constructor of B.

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