Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

inheritance

Status
Not open for further replies.

youngun

Programmer
Apr 27, 2001
61
0
0
US
I have a superclass called A, and three classes X,Y,Z inherts from A. If in A I have a private ArrayList called arr. Do my X,Y,Z all have their own ArrayList? Also, if I create a new instance x1 of type X in my main(), I am going to create a new ArrayList, right? Is there any way that I can keep only one ArrayList even though I have so many different classes? All three classes should access only one ArrayList and the data in the ArrayList should be kept across all three classes. I don't know if static works here, but I doubt it.

Thanx a lot!
 
X, Y and Z all have their own arraylist in a sense but since it is private in the parent, they inherit it but cannot use it directly.

If you want them all to share an ArrayList, you can make it static and then it will be shared amongst all instances of class A as well as the derived classes. As I said above, however, your derived classes will not be able to access this list directly since it is declared private by their parent.

"Children don't have access to their parent's privates."

Charles
 
If you wish only the subclasses of A to be able to manipulate the array, you should declare the array
Code:
protected
. This effectively makes it
Code:
private
except to any subclasses which have
Code:
public
access to it.

If you wish objects created from X, Y and Z to have shared access to the same array stored in A, you could indeed make it static, but this is not very object-oriented and is not to be recommened. It is better to create a separate object containing a single copy of the array and pass it as a parameter into each of your instantiated objects. There is no need to worry about wasting memory doing this since arrays are passed by reference (similar to pointers in C) meaning that duplicate copies are not created.

Jo.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top