Re: Inheritance Question
jsguru72 wrote:
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.
As it should. Access of field variables are not dynamically-dispatched,
like methods.
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?
Short of reflection, or overriding, no.
I.E. Short of overriding whatAmI() in each child class, what can I do
to get this program to output 'Apple' instead of 'Fruit'?
This is how I do it:
public abstract class Fruit {
protected Fruit(String type) {
this.type = type;
}
public String whatAmI() {
return this.type;
}
}
public class Apple extends Fruit {
public Apple() {
super("Apple");
}
}
Alternatively, you could define whatAmI() as follows:
public String whatAmI() {
return this.getClass().getName();
}
--
Beware of bugs in the above code; I have only proved it correct, not
tried it. -- Donald E. Knuth