Example of Protected Access
When the protected access control modifier is specified for a variable or method in a class, it can be accessed by the methods of the same class, subclasses in the same package and non-subclasses in the same package. Furthermore, protected variables and methods can be accessed by all methods of subclasses in different packages. The visibility level of a protected field lies in between the public access and package access. Note that non-subclasses in other packages cannot access the protected members.
In the following program, the variable data has been declared as protected. A subclass in another package can inherit a protected member. It would not have been possible if it has been declared as either private or package access.
Program
package mypack; public class Data { protected int data = 20; }
Program Source
import mypack.Data; class AccessData extends Data { void showData() { System.out.println("Data = "+data); } } public class Javaapp { public static void main(String[] args) { AccessData ad = new AccessData(); ad.showData(); } }