Java Program using protected access modifier

Q. Write a program to use protected access modifier in Java.

Answer:

Protected:
The protected modifier is used within same package. It can be accessed outside the package but through inheritance only.

Employee.java

class Employee
{
    protected int id = 101;
    protected String name = "Jack";
}


ProtectedDemo.java

class ProtectedDemo extends Employee
{
    private String dept = "Development";
    public void display()
    {
        System.out.println("Employee Id : "+id);
        System.out.println("Employee name : "+name);
        System.out.println("Employee Department : "+dept);
    }
    public static void main(String args[])
    {
        ProtectedDemo pd = new ProtectedDemo();
        pd.display();
    }
}


Output:

protected access modifier