This Java tutorial helps you understand the use of protected keyword in Java with code example.

Basically, the protected keyword is an access modifier for method and variable of a class.

When a method or a variable is marked as protected, it can be accessed from:

    •           Within the enclosing class.
    •           Other classes in the same package as the enclosing class.
    •           Sub classes, regardless of packages.
The main purpose of protected keyword is to have the method or variable can be inherited from sub classes.

 

Java protected keyword Examples:

The following class Person, declares a protected variable name, inside package p1:

package p1;

public class Person {
    protected String name;
}
The following class in the same package can access the variable name directly:

package p1;

public class Employer {
    void hireEmployee() {
        Person p = new Person();
        p.name = "Nam";    // access protected variable directly
    }
} 
The following class is in different package but it extends the Person class so it can access the variable name directly:

package p2;

import p1.Person;

class Employee extends Person {
    void doStuff() {
        name = "Bob";
    }
}
But the following class, in different package, cannot access the variable name directly:

package p2;

import p1.Person;

class AnotherEmployer {
    void hire() {
        Person p = new Person();
        // compile error, cannot acceess protected variable
        // from different package
        p.name = "Nam";
    }
}


The above code will cause compilation error:

AnotherEmployer.java:8: error: name has protected access in Person

 

Related keyword: public and private. See all keywords in Java.

 

Related Topics:

 

Other Recommended Tutorials:


About the Author:

is certified Java programmer (SCJP and SCWCD). He started programming with Java in the time of Java 1.4 and has been falling in love with Java since then. Make friend with him on Facebook and watch his Java videos you YouTube.



Add comment

   


Comments 

#5Hank Igoe2020-04-24 23:22
Great example, thank you
Quote
#4Bhupendra Patel2020-04-12 04:14
nice explanation sir...
thank you so much.
Quote
#3elmer2019-08-13 19:37
Noooiiicccee mate................
Quote
#2Bakswas2017-07-23 02:21
Bakwas Article..................
Quote
#1JOn2017-01-30 12:09
niiiiiiiiiiiiiiiiiiiiice
Quote