Or Smith
Or Smith

Reputation: 3616

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?

Upvotes: 0

Views: 164

Answers (2)

Moritz Petersen
Moritz Petersen

Reputation: 13057

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, e.g.:

public class A {
    public B b;

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


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

Upvotes: 2

Tim B
Tim B

Reputation: 41208

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.

Upvotes: 1

Related Questions