If this is your first visit, be sure to
check out the FAQ by clicking the
link above. You may have to register
before you can post: click the register link above to proceed. To start viewing messages,
select the forum that you want to visit from the selection below.

inheritance question

class Bag has a get method for an array value, a set method for an array value, a toString override, etc.

i want to make a class BagExt that EXTENDS the Bag class. BagExt will inherit all of Bag's methods, but will override one and maybe overload one (just trying to get familiar with how inheritance works).

so i tried to do the following . . .

public class BagExt extends Bag{

public BagExt (){
super();
}

public void add (int val){
i += val;
}

public int show_i (){
return i;
}

but when i try to compile, i get an error that "i" has private access in Bag. so do i have to declare similar variables of my own? and how is it that the default constructor will work? . . . it uses the Bag private varialbe of "int [] x".

so if i change the modifiers to protected, each object of Bag and of SetExtBag will have it's own "i". am i thinking correctly about that? and changing the value of "i" in one object will not change the value of "i" in another object since they are not static.

public gives any class access to that variable
private gives only the current class access
protected gives all subclasses access
and friendly (no specifier) gives access to all classes in the same package

you declared a private i (har har) in your Bag, and then attempted to use it from BagExt. THough it exists in BagExt, BagExt may not acces sit, because only Bag can access it. There is nothing stopping you re-declaring it in BagExt, BUT the two will NOT be linked. THis is called variable shadowing, and it is NOT RECOMMENDED because it makes programs very very hard to understand.
As noted, Bag and BagExt share i, so when you declare it as protected, if BagExt changes i, Bag feels the change too. There is only one variable called i, assigned to Bag, but accessible to BagExt.