Open In App

More restrictive access to a derived class method in Java

As private, protected and public (access modifiers) affect the accessibility and scope of the field. So, the method cannot be private which are called from outside the class. 

In Program 1 : We create the object for Derived class and call foo function, but this foo function is private i.e., its scope is only in Derived class which gives error when we want to access through Main class.

In Program 2 : We create the object for Derived class and call foo function, and this foo function is public so this will not give an error because we can access this from anywhere in package. 

In Program 3 : Here we create the object for base class and then call foo function, now foo function in both Derived and Base class must be public or protected (never private), because private method have accessibility only in that scope.

Note : Called function never be private because its scope is only in curly brackets ( {} ) if called function is in base class and is override by Derived class then overridden method in derived class is also be public or protected.

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

Output : 

prog.java:10: error: foo() in Derived cannot override foo() in Base
    private void foo() { System.out.println("Derived"); } 
                 ^
  attempting to assign weaker access privileges; was public
prog.java:16: error: foo() has private access in Derived
        d.foo();
         ^
2 errors

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

Output
Derived

Program 3




// file name: Main.java
 
class Base {
    public void foo() { System.out.println("Base"); }
}
 
class Derived extends Base {
    // if foo is private in derived class then it will
    // generate an error
    public void foo() { System.out.println("Derived"); }
}
 
public class Main {
    public static void main(String args[])
    {
        Base d = new Base();
        d.foo();
    }
}

Output
Base


Article Tags :