aspose file tools*
The moose likes Beginning Java and the fly likes access to object from another member in same package Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "access to object from another member in same package" Watch "access to object from another member in same package" New topic
Author

access to object from another member in same package

Scott A Burch
Ranch Hand

Joined: Jan 04, 2011
Posts: 50
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
Bartender

Joined: Oct 14, 2005
Posts: 18127
    
    8

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

Joined: Sep 15, 2011
Posts: 2
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

Joined: Oct 13, 2005
Posts: 36494
    
  16
And you can get all sorts of errors from declarations in the constructor, so they should be avoided like the plague.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: access to object from another member in same package
 
Similar Threads
multiple classes in a package
class accessibility
how this line works?
package problem
How to create an instance of a class that is outside of any package