开发者

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 time开发者_JS百科s. 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);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜