Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can i use same object in different classes in Java

Tags:

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.

like image 348
Vivek Avatar asked Jul 20 '11 12:07

Vivek


People also ask

Can you have many classes of the same object in Java?

With the help of the Singleton Pattern you can easily save data in one object across multiple classes.

Can an object belong to multiple classes?

An object can have multiple types: the type of its own class and the types of all the interfaces that the class implements. This means that if a variable is declared to be the type of an interface, then its value can reference any object that is instantiated from any class that implements the interface.

Can we use object of one class in another class?

You can also create an object of a class and access it in another class. This is often used for better organization of classes (one class has all the attributes and methods, while the other class holds the main() method (code to be executed)). Remember that the name of the java file should match the class name.


2 Answers

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.

like image 104
Jon Skeet Avatar answered Oct 11 '22 14:10

Jon Skeet


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 ) {
       ....
   }
}
like image 31
Ryan Ische Avatar answered Oct 11 '22 12:10

Ryan Ische