How can I use the same object in different Java classes

Suppose I have 3 Java classes A, B and C

I need to create an object of class C, which is used in both A and B, but the problem in creating the object separately is that the constructor of class c is called 2 times. But I want the constructor to be called only once.

So, I want to use an object created in class A in class b.

+4
source share
4 answers

So, create the object once and pass it to the constructors A and B:

C c = new C(); A a = new A(c); B b = new B(c); ... public class A { private final C c; public A(C c) { this.c = c; } } 

Note that this is very common in Java as a form of dependency injection, so objects are reported by their employees, not by themselves.

+15
source

Create an object C outside of A and B and create constructors A and B for an instance of class C.

 class A { public A( C c ) { .... } } class B { public B( C c ) { .... } } 
+3
source

Alternatively, if the constructors for A and B are not called next to each other, you can define Class c as singleton. See http://mindprod.com/jgloss/singleton.html

you must:

 A a = new A(C.getInstance()); B b = new B(C.getInstance()); 

or, alternatively, in the constructors for A and B just call getInstance instead of the constructor, i.e.

 // C c = new C(); C c = C.getInstance(); 
+2
source

Do you want to share a copy? Ok, how about it:

 C c = new C(); B b = new B(c); A a = new A(c); 

Another variant:

 B b = new B(); A a = new A(bc); 
0
source

All Articles