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() {}
}

class Derived extends Base {
    private void foo() {} // compiler error 
}

public class Main {
    public static void main(String args[]) {
        Derived d = new Derived();
    }
}

Program 2

// file name: Main.java
class Base {
    private void foo() {}
}

class Derived extends Base {
    public void foo() {} // works fine
}

public class Main {
    public static void main(String args[]) {
        Derived d = new Derived();
    }
}

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.






Practice Tags :
Article Tags :
Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.

Recommended Posts:



1.6 Average Difficulty : 1.6/5.0
Based on 22 vote(s)