Search code examples
javainheritancestack-overflow

Java Subclasses accessing each other


I have a basic class structure like this:

public class A {

}

public class B extends A {
    private C objC;

    public B() {
        this.objC = new C();
    }
}

public class C extends A {
    private B objB;

    public C() {
        this.objB = new B();
    }
}

I need B and C to know about each other so they can access each other's methods but obviously at runtime this creates a cyclic dependency and results in a java.lang.StackOverflowError: null. I have read this and this but I can't seem to get a good resolution on what I should do in my case.

Is there a better way to approach this?

Edit 1: A more descriptive of my situation while keeping simplicity:

public class A {

}

public class B extends A {
    private C objC;

    public B() {
        this.objC = new C();
    }

    public String foo1() {
        int x = C.foo3();
        //do something
        return Integer.toString(int);
    }

    public int foo2() {
        // do something
    }
}

public class C extends A {
    private B objB;

    public C() {
        this.objB = new B();
    }

    public int foo3() {
        int y = B.foo2();
        //do something
        return y;
    }
}

Solution

  • Use Mediator pattern if you want to establish communication among different objects.

    Mediator - defines the interface for communication between Colleague objects

    ConcreteMediator - implements the Mediator interface and coordinates communication between Colleague objects. It is aware of all the Colleagues and their purpose with regards to inter communication.

    ConcreteColleague - communicates with other Colleagues through its Mediator

    Have a look at this link : https://en.m.wikipedia.org/wiki/Mediator_pattern