Reshma Bidikar

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 error

super.b=9;

}

}

Accessing a protected field from another class in the same package

The following code snippet demonstrates how you can access a protected field from another class in the same package:

package demo;

public class AnotherClass {

public void myMethod() {

Base base = new Base();

base.b=6;

System.out.println("In another class in the same package, the value of the protected field is "+base.b);

}

}

Accessing a protected field from a different package

The following code snippet demonstrates how you can access a protected field from a different package:

package demo2;

import demo.Base;

public class AnotherClass2 {

public void myMethod() {

Base base = new Base();

base.b=7; //will cause compilation error

}

}

Accessing a protected field from a sub-class in a different package

The following code snippet demonstrates how you can access a protected field from a sub-class from a different package:

 

package demo2;

import demo.Base;

public class AnotherClass3 extends Base{


public void myMethod() {

super.b=8;

}

}

Conclusion

So in this article, you saw how the Java protected keyword can be used in various scenarios.