Java Protected Keyword explained With Code Samples
In this article, I will be covering the Java Protected Keyword. Introduction Just like private and public, protected is an access specifier. When the protected access specifier is used for a field or method, it becomes accessible in all the subclasses of the class in which the field is defined. The protected access specifier also makes the member accessible in other classes which are in the same package as the class having the protected member. Accessing a protected field from a sub-class The following code snippet demonstrates how you can access a protected field in a sub-class: package demo;public class Base {private int a;protected int b;}public class Sub extends Base {public void subMethod() {super.a=4; //this causes compilation errorsuper.b=9;}} The class Base has a private field a and a protected field b The class Sub extends Base It has a method subMethod which assigns some values to a and b a=4; – This causes a compilation error since a is private b=9 – This ...