Inheritance Question
I have a question about inheritance and member variables.
Please consider the following classes.
//Parent Abstract Class
public abstract class Fruit {
protected String fruit = "Fruit";
public String whatAmI() {
return fruit;
}
}
//Subclass
public class Apple extends Fruit {
protected String fruit = "Apple";
public Apple() {
}
public static void main(String [] args) {
Apple myApple = new Apple();
System.out.println("-->" + myApple.whatAmI() );
}
}
No matter how I try to set the fruit variable in the subclass, it
always prints out the value in the parent class.
This is just an example of the problem I am having. In my actual
environment, the whatAmI() method is much more involved. The Fruit
class will end up having as many as 50 classes that extend it. I want
to avoid having to override whatAmI() in every one of those subclasses
since 99% of the code is the same except for the value of the
variable.
I think I can understand that the whatAmI() method can only see the
fruit variable in the parent, but is there any way to set this up so
that the whatAmI() method uses the value of the fruit variable as
defined in the Apple class?
I.E. Short of overriding whatAmI() in each child class, what can I do
to get this program to output 'Apple' instead of 'Fruit'?
Thanks,
John S.