This week's book giveaway is in the Performance forum.
We're giving away four copies of The Java Performance Companion and have Charlie Hunt, Monica Beckwith, Poonam Parhar, & Bengt Rutisson on-line!
See this thread for details.
Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Method Overriding

 
Joseph Sweet
Ranch Hand
Posts: 327
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I would expect this code:



....to produce the following output:




But instead it produces:




I was wrong in the output for the 1st & 3rd lines from the end.

Why???

I am following the following tutorial:

http://www.beginner-java-tutorial.com/java-method-overriding.html

Where they say:



The following distinction between invoking instance methods on an object and accessing fields of an object must be noted. When an instance method is invoked on an object using a reference, it is the class of the current object denoted by the reference, not the type of the reference, that determines which method implementation will be executed. When a field of an object is accessed using a reference, it is the type of the reference, not the class of the current object denoted by the reference, that determines which field will actually be accessed. This is demonstrated in the above program.

 
Anton Uwe
Ranch Hand
Posts: 122
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Because "public static void method5() {..." is static and there is no "overriding" of static methods, the call "sc3.method5();" is the same as "supClass.method5();", both will be replaced by "SuperClassWithDifferentMethods.method5();".

Because method1() is overridden, "supClass.method1();" will call method1() in OverridingClass. That's exactly what overriding means.
 
Joseph Sweet
Ranch Hand
Posts: 327
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
But it does not match with what they said in the quote.

sc3 refers to OverridingClass (although sc3 is of the type SuperClassWithDifferentMethods).

Hence, according to the quote,



should have invoked the method5() that belongs OverridingClass (whether it is overridden or not) and produce:


[ March 06, 2007: Message edited by: Joseph Sweet ]
 
Anton Uwe
Ranch Hand
Posts: 122
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Calling a static method the runtime type doesn't matter.
You have declared "SuperClassWithDifferentMethods sc3=...". The compiler will substitute your sc3.method5()-call with "SuperClassWithDifferentMethods.method5();".

Edit: Please note that static methods are not instance methods.
[ March 06, 2007: Message edited by: Anton Uwe ]
 
Don't get me started about those stupid light bulbs.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic