• Post Reply Bookmark Topic Watch Topic
  • New Topic

How to access same instance of object in multiple classes  RSS feed

 
Josh Reev
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If i create an object in Class1 and save some data in that object in Class1, how can i access that same data in Class2? Here's a code sample that should clarify my situatuation:
 
William P O'Sullivan
Ranch Hand
Posts: 859
Chrome IBM DB2 Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In Class2 you need to access Class1's property (in your case ca)

Either declare ca as public and use class1.ca or use the proper get/set pattern.

To access Class1 from any other class, you need a Singleton(static) instance.

WP
 
Steve Luke
Bartender
Posts: 4181
22
IntelliJ IDE Java Python
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The best way to do that is to pass the Object from one class to another. So if you make an instance of Class2 inside Class1, you might do this:



If Class1 doesn't know about Class2, but Class2 knows about Class1 then you can use a getter method:


If Class1 doesn't know about Class2 and Class2 doesn't know about Class1, then there needs to be some controller class which knows about both. Class1 would allow others to get the ClientArray, and Class2 would be assigned the ClientArray:


Finally, if Class1 doesn't know about Class2, and Class2 doesn't know about Class1, and there is no Controller type thing which both know about, then there needs to be some shared Scope object to hold the value. Class1 would pass the value to the Scope and Class2 would take the value from the Scope.
 
Josh Reev
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for your efforts, it looks like i can achieve what i want by creating ClientArray like this:

and getInstance looks like this:
 
Steve Luke
Bartender
Posts: 4181
22
IntelliJ IDE Java Python
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Before you get into using a Singleton for this, I would suggest you take a search around forum (or the net in general) on the proper use of Singletons. It can be debated as to what the appropriate use of them are, but there are good discussions about whether to use them 'because they are easier' as opposed to some other approach which may be more resilient and Object-Oriented friendly.

For example: this recent thread has a pretty good discussion on the subject. And it also has some great links that describe the things to consider in great detail.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!