Get an existing object from another class

I am very new to programming and want to know if I can somehow get an object from a class in which I already used new MyClass(); to use it in another class and that I no longer need to use new MyClass(); . I hope you understand.

The example is very simple:

 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() } 
+7
java object class
source share
6 answers

You can use Singleton pattern to achieve this.

This is an example of launching such an object. It has a private constructor and an open class getInstance method :

static methods that have a static modifier in their declarations must be called with the class name, without the need to instantiate the class

When we call getInstance , it checks to see if an object has already been created and will return an instance of an already created object; if it has not been 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 this works, 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."); } 
+2
source share

Since you just started coding, you won’t give you a term like reflection, and that’s it .. here’s one of the easiest ways to get the public getter() method.

Consider this simple example.

 class Something { private int a=10; public int getA() { return a; } } 

Here is the first one that has a public method that returns 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; } } 

Access to 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 have not checked

Enter this function in MyFirstClass

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

and then print the hash codes of 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 you are indeed using the object created in MyFirstClass in MySecondClass .

Because it will give you the same hashcode output.

Conclusion On my machine.

 Something@2677622b Something@2677622b 
+3
source share

The syntax pattern allows you to have one instance that is globally accessible to other classes. This template “guarantees” that you have only one instance in memory. There are exceptions to one advantage, for example, when deserializing from a file, unless you take care and readResolve .

Please note that in the Something class there is no state (fields) directly, only behavior, therefore it is safe to share between multiple threads. If something was able, you will need to provide some kind of synchronization mechanism in a multi-threaded environment.

Given such syntax without syntax, it would be better to replace it with a class that contains only static methods. That is, if you do not implement a template, such as a strategy that requires an interface, then it would be nice to cache an instance like the one below with a Singleton template.

You have to remake 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() { //.. } } 
+1
source share

Instead of using the Singleton pattern, the best pattern to use is dependency injection. Essentially, you create an instance of the class you want to share, and pass it in the constructor of each class that it needs.

 public class MainClass { public static void main(String[] args) { SharedClass sharedClass = new SharedClass(); ClassA classA = new ClassA(sharedClass); ClassB classB = new ClassB(sharedClass); } } public class ClassA { private SharedClass sharedClass; public ClassA(SharedClass sharedClass) { this.sharedClass = sharedClass; } } public class ClassB { private SharedClass sharedClass; public ClassB(SharedClass sharedClass) { this.sharedClass = sharedClass; } } 
+1
source share

If FirstClass and SecondClass are somehow related, you can retrieve this shared object that you use for the superclass, and this is the only area in which you plan 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 this instance somewhere else, you should use the Singleton object. The easiest way to do this:

 enum Singleton { INSTANCE; private final Something obj; Singleton() { obj = new Something(); } public Something getObject() { return obj; } } 

You use it:

 Singleton.INSTANCE.getObject(); 
+1
source share

Well, firstly, you can use inheritance, for example.

 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 do not need any objects and only a method, you can implement interfaces, for example.

 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() } 
+1
source share

All Articles