More restrictive access to a derived class method in Java
In Java, it is compiler error to give more restrictive access to a derived class function which overrides a base class function. For example, if there is a function public void foo() in base class and if it is overridden in derived class, then access specifier for foo() cannot be anything other than public in derived class. If foo() is private function in base class, then access specifier for it can be anything in derived class.
Consider the following two programs. Program 1 fails in compilation and program 2 works fine.
Program 1
// file name: Main.java class Base { public void foo() { System.out.println("Base"); } } class Derived extends Base { // compiler error private void foo() { System.out.println("Derived"); } } public class Main { public static void main(String args[]) { Derived d = new Derived(); d.foo(); } } |
chevron_right
filter_none
Program 2
// file name: Main.java class Base { private void foo() { System.out.println("Base"); } } class Derived extends Base { // works fine public void foo() { System.out.println("Derived"); } } public class Main { public static void main(String args[]) { Derived d = new Derived(); d.foo(); } } |
chevron_right
filter_none
Output:
Derived
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Recommended Posts:
- Access and Non Access Modifiers in Java
- Method Class | getName() Method in Java
- Method Class | getParameterAnnotations() method in Java
- Method Class | hashCode() Method in Java
- Method Class | equals() Method in Java
- Method Class | getTypeParameters() Method in Java
- Method Class | getExceptionTypes() Method in Java
- Method Class | getGenericParameterTypes() method in Java
- Method Class | getModifiers() method in Java
- Method Class | getDeclaredAnnotations() method in Java
- Method Class | getParameterCount() method in Java
- Method Class | getAnnotation() method in Java
- Method Class | isVarArgs() Method in Java
- Method Class | toGenericString() method in Java
- Method Class | getAnnotatedReturnType() method in Java



