wood burning stoves 2.0*
The moose likes Beginning Java and the fly likes Method Overriding Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Method Overriding" Watch "Method Overriding" New topic
Author

Method Overriding

Joseph Sweet
Ranch Hand

Joined: Jan 29, 2005
Posts: 327
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.



We must know, we will know. -- David Hilbert
Anton Uwe
Ranch Hand

Joined: Jan 10, 2007
Posts: 122
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

Joined: Jan 29, 2005
Posts: 327
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

Joined: Jan 10, 2007
Posts: 122
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 ]
 
GeeCON Prague 2014
 
subject: Method Overriding