Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get an already existing object from another class

Tags:

java

object

class

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()
}
like image 756
RagnarLodbrok Avatar asked Jun 15 '15 18:06

RagnarLodbrok


1 Answers

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
like image 60
Ankur Anand Avatar answered Nov 03 '22 01:11

Ankur Anand