java - where does downcasted object point to? -
public class animal{ int n = 5; public static void main(string[] args) { animal = new animal(); animal ah = new horse(); horse h = new horse(); system.out.println(h.n); // prints 7 system.out.println(ah.n); // prints 5 h = (horse) ah; system.out.println(h.n); // prints 7 } } class horse extends animal{ int n = 7; }
my question:
why h.n
still print 7 after h = (horse) ah
? after assignment should point same object ah
points , n field points 5?
first, let's call field n
of class animal
"animal.n
" avoid confusion.
fields, unlike methods, not subject overriding. in horse class, may think overriding value of animal.n
7, declaring new variable called n
(let's call horse.n
avoid confusion).
so really, have class called horse
2 fields: animal.n
, horse.n
. field when "n
" depends upon static type of variable @ time.
when have object type horse
, upcast animal
, n
field refers animal.n
, , has value of "5". hence ah.n
"5".
when have same object, downcast again horse
, n
field refers horse.n
, , has value of "7". hence h.n
"7".
to clarify: indeed, h
point same object ah
points -- downcasting not change object being pointed at. however, static type affect field of object being requested.
Comments
Post a Comment