Well, I have not completely wrapped my head around this concept either, but I thought I'd take a poke at it anyway.
Obviously, you have overridden getY(), but when you create a variable with the same identifier in a subclass as is in the superclass, there is no overriding taking place. It is simply that you are using the same name again (similar to declaring a variable inside a method with the same identifier as a member variable).
Upon initialization of SubShape, a Shape object must first be "created" so that a SubShape object can be built around it.
Let's go for an analogy here:
There is a Car class. It has a member variable color and an instance method drive(). There is a subclass of Car called Focus which has its own member variable called color and it has overridden drive() with
e73
its own drive() method.
Let's use our imaginations for a moment. At the assembly plant they get a Car and want to turn it into a Focus. The first thing they do is notice that drive is overridden meaning: don't drive like a car, drive like a Focus. They take the Car engine out and put a Focus engine in there.
The next thing they do is see that Focus has a color property. They
spray the paint on the car which masks the original color, and it becomes a Focus. What they have not done here is to first remove the old paint of the Car before applying the new paint of the Focus (which is what happened with the drive() method), they just painted over it.
Now, when an object is referred to using an identifier of a superclass, any properties and/or methods that were added on since it was just a car are now "invisible"(only from accessiblity land, not for good). This means that the new color is no longer masking the other color, but the engine (since it was replaced, not modified) stays. All we're left with for color is whatever the color property of the Car is, before it was masked by the color of the Focus.
Try it out:
class Car {
String color = "Silver";
public void drive(){
System.out.println("putt putt putt");
}
}
class Focus extends Car {
String color = "Red";
public void drive(){
System.out.println("Vrooom Vroooom");
}
}
class Driver {
public static void main(String[] args){
Focus f = new Focus();
Car c = f;
f.drive();
c.drive();
System.out.println(c.color);
System.out.println(f.color);
}
}
[This message has been edited by Paul Caudle (edited June 12, 2000).]