Get an already existing object from another class

13,938

Solution 1

You can use Singleton pattern to achieve this

This is kickoff example of such object. It has a private constructor and public class method getInstance:

static methods, which have the static modifier in their declarations, should be invoked with the class name, without the need for creating an instance of the class

When we make a call to getInstance it checks if an object has been created already and will return an instance of already created objected, if it wasn't created it will create a new object and return it.

public class SingletonObject {

private static int instantiationCounter = 0;    //we use this class variable to count how many times this object was instantiated

private static volatile SingletonObject instance;
private SingletonObject() { 
    instantiationCounter++;
}

public static SingletonObject getInstance() {
    if (instance == null ) {
       instance = new SingletonObject();
    }

    return instance;
}

public int getInstantiationCounter(){
    return instantiationCounter;
}
}

To check how does this work you can use the following code:

public static void main(String[] args)  {
        SingletonObject object = SingletonObject.getInstance();

        System.out.println("Object was instantiated: " + object.getInstantiationCounter() + " times.");

        object = SingletonObject.getInstance();

        System.out.println("Object was instantiated: " + object.getInstantiationCounter() + " times.");

        object = SingletonObject.getInstance();

        System.out.println("Object was instantiated: " + object.getInstantiationCounter() + " times.");

    }

Solution 2

Since you have just started coding won't give you a term like reflection and all.. here is one of the simple way is have a public getter() method.

Consider this simple example

class Something {

    private int a=10;

    public int getA() {
        return a;
    }


}

Here is the First which has a public method which return the object that i created in this class for the Something Class

class MyFirstClass {

    private Something st;

    public MyFirstClass() {
        this.st = new Something();
    }

    public Something getSt() {
        return st;
    }




}

Accessing it from another Class

class MySecondClass {

    public static void main(String...strings ){
        MyFirstClass my =new MyFirstClass();
        System.out.println(my.getSt().getA());
    }


}

Output: 10

If You wan't to verify

Inject this function in MyFirstClass

public void printHashcode(){
        System.out.println(st);
    }

and then print the hash codes from both methods in MySecondClass

class MySecondClass {

public static void main(String...strings ){
    MyFirstClass my =new MyFirstClass();
    System.out.println(my.getSt());
    my.printHashcode();

}

}

You will see that indeed you are using the Object created in MyFirstClass in MySecondClass.

Because this will give you same hashcode output.

Output On my machine.

Something@2677622b
Something@2677622b

Solution 3

Okay firstly you can use inheritance e.g.

class MyFirstClass

{

Something st = new Something();

}

class Something()
{
// some code
}

class MySecondClass extends myFirstClass
{
// This is where I want to use the object from class Something()
// like
MySecondClass obj = new MySecondClass();
obj.method();  //Method from myfirstclass accessible from second class object

}

Or if you dont want any objects and just the method you can implement interfaces e.g.

public interface MyFirstClass
{

//example method
 public abstract void saying();    //no body required

Something st = new Something();
}

class Something()
{
// some code
}

class MySecondClass implements MyFirstClass //Have to implement methods
{

   public void saying(){         //Method implemented from firstClass no obj
   System.out.println("Hello World");
 }
 getObjectFromClass()
}

Solution 4

Singleton pattern lets you have single instance which is 'globally' accessible by other classes. This pattern will 'guarantee' that you have only one instance in memory. There are exceptions to one instance benefit, such as when deserializaing from file unless care is taken and readResolve is implemented.

Note that class Something right now has no state(fields), only behavior so it is safe to share between multiple threads. If Something had state, you would need to provide some kind of synchronization mechanism in multi thread environment.

Given such stateless Singleton, it would be better to replace it with class that contains only static methods. That is, unless you are implementing pattern such as Strategy which requires interface implementation, then it would be good idea to cache instance like bellow with Singleton pattern.

You should rework your Something class like this to achieve singleton:

public class Something {

    private static final Something INSTANCE = new Something ();

    private Something () {

        // exists to defeat instantiation
    }

    public Something getInstance() {
        return INSTANCE;
    }


    public void service() {
        //...
    }

    public void anotherService() {
        //..
    }
}

Solution 5

If FirstClass and SecondClass are somehow related, you can extract that common object you're using to a super class, and that's the only scope in which you're planning to use this object.

    public class SuperClass{
        Something st = new Something();

        public Something getObjectFromClass(){
           return st;
        }
    }

    public class MyFirstClass extends SuperClass{
       getObjectFromClass();
    }

    public class MySecondClass extends SuperClass{
       getObjectFromClass();
    }

Otherwise, if you plan to use that instance somewhere else you should use a Singleton object. The easiest way of doing this is:

enum Singleton
{
    INSTANCE;

    private final Something obj;

    Singleton()
    {
        obj = new Something();
    }

    public Something getObject()
    {
        return obj;
    }
}

You use it:

Singleton.INSTANCE.getObject();
Share:
13,938
nintschger
Author by

nintschger

Updated on June 17, 2022

Comments

  • nintschger
    nintschger almost 2 years

    Im very new to programming and want to know if I can somehow get the object from a class where I already used new MyClass(); to use it in another class and that I don't need to use new MyClass(); again. Hope you get the point.

    Some very simple example:

    class MyFirstClass
    {
        Something st = new Something();
    }
    
    class Something()
    {
        // some code
    }
    
    class MySecondClass
    {
        // This is where I want to use the object from class Something()
        // like
        getObjectFromClass()
    }