how do you restrict a member of a class from inheriting to it’s sub classes?

We can restrict a member of a class from inheriting to it’s sub classes by declaring the member as a private. Because, private members are not inherited to sub classes. Example

class Student
{   
    String name = "Jai";
    private int rollNo = 11;
}
public class Main extends Student
{
    void show(){
        System.out.println(name);
        System.out.println(rollNo);
    }
    public static void main(String[] args)
    {
        Main object = new Main();
        object.show();
    }
}

Output

Main.java:17: error: rollNo has private access in Student
        System.out.println(rollNo);
                           ^
1 error

Java interview questions on Inheritance

Please follow and like us:
Content Protection by DMCA.com