This week's book giveaway is in the OCAJP forum.
We're giving away four copies of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) and have Khalid A Mughal & Rolf W Rasmussen on-line!
See this thread for details.
Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

access to object from another member in same package

 
Scott A Burch
Ranch Hand
Posts: 63
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
How can a class access the value of an object from another class in the same package?

For example:



How would Class Two in the same package access the Date object someDate?

### thank you
 
Paul Clapham
Sheriff
Posts: 21314
32
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That isn't an example of "an object from another class". In your example the someDate variable is a local variable in class One's constructor. As such, any object assigned to it is unreferenced as soon as the constructor terminates execution, and that object becomes available for garbage collection. Nothing anywhere has (or can have) access to it after that moment.
 
Catalin Roncea
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,

I agree with Paul.
Here are my ideas on your case:

How would Class Two in the same package access the Date object someDate?


In class "One":
1. create a private variable "someDate " of type Date;
2. create a getter for "someDate" (can be "package access" if you want only in the package to be accessed)
3. initialize "someDate" in constructor (in your case: public One(SingleFrameApplication app) )

In class "Two":
1. create an object for class "One" by calling the constructor
2. get the value from "someDate" using the getter

If you don`t want to always create a new instance for class "One" I suggest you design class "One" as a Singleton.

Another option will be to declare your variable "someDate" as public static and initialize it in the constructor and then get it like this: One.someDate. I really do not recommend this way.





 
Campbell Ritchie
Sheriff
Pie
Posts: 49733
69
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
And you can get all sorts of errors from declarations in the constructor, so they should be avoided like the plague.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic