Hi Nick Marino,
First of all, a warm welcome to CodeRanch!
Nick Marino wrote:What throws me off is that when I debug this I can clearly see that the gearRatio of the super class is hidden which would imply that the out put is going to see and use the shadowed variable.
Which IDE/tool are you using? Because I have never seen this representation (with reference of the hidden field and value). Apparently Eclipse also mentions both
gearRatio variables, but it mentions nothing but the variable names
Nick Marino wrote:ok but what does hidden mean in the debug image I included, doesn't that mean the seen value is 9, yet the code outputs the super classes gearRatiao value.
Maybe I am miss reading that debug message, am I to assume that to the Sportscar instance its hidden so the only other value to return is 8 from the super class.
The debug message is pretty useless with this code snippet. It would be useful if you replace the
accelerate method in
SportsCar with this code
With this code the debug message is very helpful:
line1 will print the yellow
gearRatio and
line2 will print the hidden
gearRatio.
But with the code snippet from the
main method it's completely useless
The reason why is already very well explained by Joe Bishara: the
gearRatio is resolved at compile-time, not at runtime (and your debug message - like mine from Eclipse - is created at runtime).
Finally I share some very easy but
very important rules:
1/ Which instance methods you can call/invoke is determined at compile time based on the reference variable type. Which instance method is actually executed is decided at runtime based on the type of the actual object (=
polymorphism)
2/ Which instance variables you can access is determined at compile time based on the reference variable type. (no polymorphism with fields in
Java)
3/ Which class variables and methods you can access is determined at compile time based on the reference variable type. (no polymorphism with class variables and methods in Java)
And don't forget: with class variables and methods you don't need an instance to access/invoke these methods. So what do you think the result of this code will be?
Hope it helps!
Kind regards,
Roel