Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

The keyword protected

The keyword protected: The protected modifier exposes a member within its package and to subclass code under special inherited-access rules.

Version: Java SE 21 (JLS and Java SE API); examples verified on the repository Java runtime

Syntax

protected

The protected modifier exposes a member within its package and to subclass code under special inherited-access rules.

Use protected for narrow subclass extension points, preferring methods over directly mutable fields.

In a subclass from another package, protected does not permit access through any base-class instance; the qualifying expression must satisfy the subclass rule.

A protected constructor supports package code and subclass construction, while protected static access has a related qualifier rule.

The subclass prints value=base and protected=true confirms the inherited method modifier.

Examples

public class Main { static class Base { protected String value(){return "base";} } static final class Child extends Base { String read(){return value();} } public static void main(String[] a)throws Exception{System.out.println("value="+new Child().read());System.out.println("protected="+java.lang.reflect.Modifier.isProtected(Base.class.getDeclaredMethod("value").getModifiers()));} }

Result

value=base
protected=true

The subclass prints value=base and protected=true confirms the inherited method modifier.

Sources