Private and final methods in Java
When we use final specifier with a method, the method cannot be overridden in any of the inheriting classes. Methods are made final due to design reasons.
Since private methods are inaccessible, they are implicitly final in Java. So adding final specifier to a private method doesn’t add any value. It may in-fact cause unnecessary confusion.
class Base {
private final void foo() {}
}
|
For example, both ‘program 1’ and ‘program 2’ below produce same compiler error “foo() has private access in Base”.
Program 1
class Base {
private final void foo() {}
}
class Derived extends Base {
public void foo() {}
}
public class Main {
public static void main(String args[]) {
Base b = new Derived();
b.foo();
}
}
|
Program 2
class Base {
private void foo() {}
}
class Derived extends Base {
public void foo() {}
}
public class Main {
public static void main(String args[]) {
Base b = new Derived();
b.foo();
}
}
|
Last Updated :
27 May, 2017
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...