KnowledgeBoat Logo
|

Computer Applications

With the help of an example explain how you can access a private member of a base class.

Encapsulation & Inheritance in Java

18 Likes

Answer

Private member of a base class can be accessed through a public method of the base class which returns the private member. This is illustrated in the example below:

class A {
    private int x;

    public A() {
        x = 10;
    }

    public int getX() {
        return x;
    }
}

class B extends A {
    public void showX() {
        System.out.println("Value of x = " + getX());
    }
}

Answered By

10 Likes


Related Questions