简体   繁体   中英

How can i use same object in different classes in Java

Suppose i have 3 java classes A, B and C

I need to create an object of class C that 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 just once.

So i want to use the object created in class A into class b.

So create the object once, and pass it into the constructors of 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 such that objects are told about their collaborators rather than constructing them themselves.

Create object C outside of both A and B and have the constructors of A and B accept an instance of class C.

class A {
   public A( C c ) {
       ....
   }
}

class B {
   public B( C c ) {
       ....
   }
}

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

you would then do:

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

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

// C c = new C();
C c = C.getInstance();

You want to share an instance? Ok, how about his:

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

Another option is:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM