posted 24 years ago
S2 is inheriting S1's display() method and working fine. What's confusing is what it's printing it out - because you've got a String s variable in both classes. S2 inherits S1's String s and that's what the display() method is using. If you declare and initialise a class member variable with the same name in a parent and a child class, you will always end up with a variable set to the value specified in the parent class when you create an instance of the sub-class. You can either change the value in the constructor of the sub-class or change it after the instance is created.
So if you want to set s to something different for the S2 sub-class, you need to set it in a constructor like this:-
class S2 extends S1{
S2()
{
s = "S2";
}
}
Hope that helps,
Kathy