7

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.

4 Answers 4

17

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.

Sign up to request clarification or add additional context in comments.

Comments

3

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 ) {
       ....
   }
}

Comments

2

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();

1 Comment

I agree with @JonSkeet that the DI style of adding C as a constructor parameter is a common (and useful) design pattern in Java
0

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.