GeeCON Prague 2014*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Can final method be overridden? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Can final method be overridden?" Watch "Can final method be overridden?" New topic
Author

Can final method be overridden?

Moya Green
Ranch Hand

Joined: Jan 24, 2002
Posts: 49
http://home.att.net/~p.durairaj/myexam.html
Q#14. Consider the code bellow.
class WF {
private final void f() {
System.out.println("WF.f()");
}
private void g() {
System.out.println("WF.g()");
}
}
class OP extends WF {
public final void f() {
System.out.println("OP.f()");
}
public void g() {
System.out.println("OP.g()");
}
}
public class Overriding {
public static void main(String[] args) {
OP op = new OP();
op.f();
op.g();
WF wf = op;
((OP)wf).f();
((OP)wf).g();
}
}
Code complied and run OK. It gave the output of OP.f() OP.g() OP.f() OP.g()
I think final method can not be overriden. But in this code it worked. Can anyone explain this? Thank you in advance!
Moya
Anthony Villanueva
Ranch Hand

Joined: Mar 22, 2002
Posts: 1055
Please note that you declared f() and g() in your superclass as private, which means they cannot be overriden. As far as the compiler is now concerned, f() of the superclass and the subclass are totally unrelated. If you take away this modifier your code will not compile, as you are attempting to override a method that is declared final.
Anthony Villanueva
Ranch Hand

Joined: Mar 22, 2002
Posts: 1055
Here's an example to demonstrate that no override is going on. Please note I declared the classes as inner classes only to work around the fact that the superclass method is declared private.
Moya Green
Ranch Hand

Joined: Jan 24, 2002
Posts: 49
Anthony,
Good explaination! Thank you so much.
Moya
Vin Kris
Ranch Hand

Joined: Jun 17, 2002
Posts: 154

I'm getting a compilation error.
Test.java:7: Superclass Super of local class Sub (Test. 1$Sub) not found.
class Sub extends Super
^
Barkat Mardhani
Ranch Hand

Joined: Aug 05, 2002
Posts: 787
I did not get any error with 1.3 compiler.
Ron Newman
Ranch Hand

Joined: Jun 06, 2002
Posts: 1056
Neither do I, with 1.3.1 compiler on a Mac.
What compiler are you using?


Ron Newman - SCJP 1.2 (100%, 7 August 2002)
Vin Kris
Ranch Hand

Joined: Jun 17, 2002
Posts: 154
JDK 1.2.2 Release 10 on Solaris. It compiles on JDK 1.4.1.
Only one thing to do. go hunt for bugs. Somebody should have surely swatted this bug.
[ September 25, 2002: Message edited by: Vin Kris ]
 
GeeCON Prague 2014
 
subject: Can final method be overridden?