so casting to a parent class overrides the accessible methods in the subclass?
Casting has nothing to do with
overriding anything.
Casting is used to make compatible assignments between object references while keeping the actual runtime type of the object instance unchanged.
PolyA ref1 = new PolyC();
Here Clement made an object of type PolyC pointed to by an object reference of type PolyA. Objects by themselves are not publicly visible; they can only be accessed indirectly through object references.
The type of an object and the object reference pointing to that object need not be the same, but there must an inheritance relationship at least, where the type of the object reference is a
supertype of the object instance. Otherwise it will not compile. The code above works because PolyA is a supertype of the object instance.
PolyB ref2 = (PolyB)ref1;
Two things are happening here:
(1) Clement is casting the object reference
ref1 which is of type PolyA to type PolyB, because the assignment is a
narrowing conversion.
(2) The object reference
ref2 is now pointing to the instance object (which is still of type PolyC). Now both
ref1 and
ref2 are pointing to the same object. The code above works too because PolyB is also supertype of the object instance.
System.out.println(ref2.g());
Java uses
dynamic method lookup to resolve which method it will call. Basically it goes like this:
The Java genie inside the box says to himself: :roll:
"I have an object reference ref2 invoking an overriden method g().
Inside the object reference ref2 is the object instance.
What is the type of this object instance? It is PolyC.
What is the highest superclass of PolyC with a non-private g() defined? It is PolyA.
Is g() in PolyA overriden by a subclass? Yes, it is overriden by PolyB.
I now examine g() of PolyB.
Is g() in PolyB overriden by a subclass? No, therefore this is the method I must invoke."
Invoking g() of PolyB the Java Genie notices another method invocation: this.f(). He repeats the above procedure, determining that the
this object reference holds an object instance of type PolyC. Listening in...
"...What is the type of this object instance? It is PolyC.
What is the highest superclass of PolyC with a non-private f() defined? It is PolyB..
Is f() in PolyB overriden by a subclass? No (since it is private), therefore this is the method I must invoke."
And so he invokes f() of PolyB, which returns 1.
-anthony