If class A has a reference of class B and class B has a reference of class A, is it acceptable in Java?
Yes.
When we execute class A by the time class B will not be instantiated. So how the compiler will execute the reference of class B?
You have to create the cyclic reference by creating one object first, and then the other, and then closing the cycle; e.g. something like this.
A a = new A();
B b = new B(a);
a.setB(b);
(This assumes that the A
class has been defined with a setB(A)
method. There are other ways to form the cycle too, but this is the simplest.)
But note that your terminology is all completely wrong.
- You don't "execute" a class. You instantiate or create an instance of a class.
- The compiler (for example
javac
) doesn't "execute" anything ... it just compiles code.
- The thing that executes (i.e runs) Java code is a Java Virtual Machine; e.g. when you use the
java
command.
(It is important that you learn and use the correct Java terminology if you are going to communicate with other IT professionals. It avoids a lot of miscommunication and confusion!)