KnowledgeBoat Logo
|

Computer Applications

In what way does the access specifier of the base class have access control over the derived class? Show with the help of an example.

Encapsulation & Inheritance in Java

12 Likes

Answer

Access specifier of the base class have access control over the derived class in the following way:

  1. Private members of base class cannot be accessed in the derived class.
  2. Public members of base class can be accessed as public members in the derived class.
  3. Protected members of base class can be accessed in the derived class and can be inherited by further sub classes.

Below example illustrates this:

class A {
    public int x;
    protected int y;
    private int z;

    public A() {
        x = 10;
        y = 20;
        z = 30;
    }

    public int sum() {
        return x + y + z;
    }
}

class B extends A {
    int total;

    void computeTotal() {
        /*
         * Public method sum() of base class
         * is accessible here
         */
        total = sum();
    }

    void display() {
        /*
         * x is accessible as it is public
         */
        System.out.println("x = " + x);

        /*
         * y is accessible as it is protected
         */
        System.out.println("y = " + y);

        /*
         * This will give ERROR!!!
         * z is not accessible as it is private
         */
        System.out.println("z = " + z);
    }
}

Answered By

7 Likes


Related Questions