Computer Applications

What is the significance of using protected declaration during inheritance? Show with the help of an example.

Encapsulation & Inheritance in Java

26 Likes

Answer

A class member declared as protected can be accessed directly by all the classes within the same package and the subclasses of its class even if the subclasses are in different packages. Example:

class A {
    protected int amount;
}

class B extends A {
    public void displayAmount() {
        System.out.println("Amount = " + amount);
    }
}

Answered By

14 Likes


Related Questions