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.
With the help of the Singleton Pattern you can easily save data in one object across 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.
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.
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 ) {
....
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With