(Field hiding) When does it make sense to use both a subclass field and its hidden superclass field?

107 Views Asked by At

In Java (as with most OO languages), you can have two classes, with one extending the other. You can have instance fields with the same name in both classes, where the subclass' instance field hides the superclass' instance field. An example is written below.

class A{
    int i;
}

class B extends A{
    int i;
}

This means that when the object is created, it has both its B instance field, i, and its A instance field, i. One might think that you would never want this, and that when you conceptually create a new "i" in class B, it means "the one and only i that is relevant to this object". When is this not the case? Give an example of two classes where we want to keep both instance variables and modify them.

0

There are 0 best solutions below