aspose file tools*
The moose likes Beginning Java and the fly likes Using Arrays Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Using Arrays" Watch "Using Arrays" New topic
Author

Using Arrays

Landon Blake
Ranch Hand

Joined: Dec 04, 2003
Posts: 121
If I have an array held in a "public" object, can I access that array from the method of another object? Does the array also have to be declared as public?
Also, is there a way to "import" an array into an object so it's values can be accessed just like the object's member varaibles?
Thanks
Marc Peabody
pie sneak
Sheriff

Joined: Feb 05, 2003
Posts: 4727

To avoid the details of protected and (default), I'll just say you can access the array directly from another object if the array is public. You can not access it directly if it is private.
If your array was marked as private, you can still provide access to it through what is called an accessor method which might look something like this:
public String[] getMyArray(){
return myArray;
}
What you asked about "importing" can be done if your second class contains a class-level variable, like so:
private String[] importedArray = null;
and then populate it in one of your methods with a call to the first class that originally holds the array, like so:
importedArray = object1.getMyArray();
Note that this can be dangerous because both classes now have a reference to the same object. It does NOT create a copy of the object. It's like having two TV remotes for the same TV and giving one to someone else in your house. Just think of how confused Class1 would be if she thought Apprentice was on the tube and some other class had changed it to PBS!


A good workman is known by his tools.
Landon Blake
Ranch Hand

Joined: Dec 04, 2003
Posts: 121
Thanks for the response Marc.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Using Arrays
 
Similar Threads
Casting arrays
array as an object?
BufferedImage from byte[]
How do I access this array???
How to implement expandable array