I have a UML that I have to convert to Java code. The only thing I cannot figure out is how to call method op2() in class B from classes C and D. If I create an object of class B, then the whole program goes into an infinite loop. And I cannot even make the method op2() a class method. Can anyone tell me where I need to correct the code?

Code:
public class B extends A {
public static void main(String args[]) {
new B();
}
private C c;
private D d;
public B() {
System.out.println("B()");
c = new C(this); // 1:
d = new D(this); // 2:
c.op3(d); // 3:
d.op4(c); // 4:
}
public void op2() {
System.out.println("B.op2()");
op1(); // 3.1.1.1: and 4.1.1.1:
}
}
class A{
public void op1() {
System.out.println("A.op1()");
}
}
class C {
private B b;
private D d;
public C(B b) {
System.out.println("C()");
}
public void op3(D d) {
System.out.println("C.op3()");
d.op5();
}
public void op5() {
System.out.println("C.op5()");
b.op2(); //erroneous part
}
}
class D {
private B b;
private C c;
public D(B b) {
System.out.println("D()");
}
public void op4(C c) {
System.out.println("D.op4()");
c.op5();
}
public void op5() {
System.out.println("D.op5()");
b.op2(); //erroneous part
}
}
Bookmarks