A protected field or method in a public class can be accessed directly by all classes within the same package and its subclasses even if the subclasses are in different packages. It is more restrictive than default (or package) access.
class Num //super class
{
protected int x,y; //protected Members
Num(int a, int b)
{
x=a;
y=b;
}
public void showxY()
{
System.out.println("x = " + x);
System.out.println("y = " + y);
}
}
class Result extends Num
{
private int z ;
Result(int a,int b)
{
super(a,b);
}
public void add()
{
z = x+y;
}
public void show()
{
System.out.println("z = " + z);
}
}
public class ProtectedInheritance
{
public static void main(String[] args)
{
Result d = new Result(5,6);
d.showxY();
d.add();
d.show();
}
}
In the above program, we create a superclass Num having protected fields x and y and a method showXY (). Then we derive a/subclass Result ,from Num which contains its own data field z and two methods add () and showZ(). The data fields x and y of superclass Num are declared as protected because we want that the method add () of the subclass can access it directly. In main () , we instantiate the object of subclass Result and initialize the fields x and y of superclass Num with values 5 and 6 respectively using a call to the constructor. Then the method add () is called, to calculate the sum of x and y and display the result using showZ() method.