• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Can final method be overridden?

 
Moya Green
Ranch Hand
Posts: 49
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 1055
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 1055
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 49
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Anthony,
Good explaination! Thank you so much.
Moya
 
Vin Kris
Ranch Hand
Posts: 154
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

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
Posts: 787
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I did not get any error with 1.3 compiler.
 
Ron Newman
Ranch Hand
Posts: 1056
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Neither do I, with 1.3.1 compiler on a Mac.
What compiler are you using?
 
Vin Kris
Ranch Hand
Posts: 154
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic