Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

private and final ?

 
aravind arav
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,
Look at the follwing code,its compiling without any error.My doubt is..In class A ive declared method f to be final & private but still am able to override it in class B. But,as far as i know final methods cannot be overidden!.Only when am using final with private am able to override it,otherwise not.Please explain !

import java.io.*;
class A{
private final void f(){
System.out.println("hello");
}
}

class B extends A{
void f(){
System.out.println(i);
}
public static void main(String s[]){
B b = new B();
b.f();
}
}
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15216
36
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Final methods cannot be overridden, that's correct.

But also: private methods are not inherited. The method f() in class A isn't visible in class B, because it's private in class A.

The method f() in class B does not override the method f() in class A, because class B simply doesn't see the f() in class A. The f() in class B should be regarded as a completely different method which has no connection to the f() in class A.
 
aravind arav
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
okay .. got it! Thank you jesper young ..
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic