File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes Method overriding - special cases: Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Method overriding - special cases:" Watch "Method overriding - special cases:" New topic

Method overriding - special cases:

Thomas Markl
Ranch Hand

Joined: Mar 08, 2001
Posts: 192
iIf an Instance method is overridden then the object type will determine the
Invoked method. In this case method f() is not overridden but new defined
as there is a private access modifier.
If a method is not overridden but new defined then the reference type accounts
for the method invocation. But in this case the reference type and the object
type is Sub, so why isn’t there f() in Sub called?

Here it is the same. For a static method only the reference type counts
for method invocation of „overridden / = hidden) static method.
But here the object AND reference type is Sub, so why call f() in Tester3?

C:\Java\EigeneJavaProgramme>java Tester3
Dirk Schreckmann

Joined: Dec 10, 2001
Posts: 7023
You are discovering and further defining what is meant by "static members (and private members) don't participate in polymorphism."
These examples of non-participation are perhaps a bit suprising (at least they were for me) at first.
Whenever the compiler can inline a static or private method invocation, it does. The implementation of g() is found in the super class and because the implementation of f() is private (or static in your second example) in the super class, the compiler looks no further than the super class for it - it gets inlined.
So, once again, private instance members and static class members don't participate in polymorphism.

[How To Ask Good Questions] [JavaRanch FAQ Wiki] [JavaRanch Radio]
I agree. Here's the link:
subject: Method overriding - special cases:
It's not a secret anymore!