Java Keyword Protected

The reserved keyword protected is used with the declaration of a Java method, Java variable, or Java inner class. Protected variables can only be accessed by members of their own class or classes from the same package.

Dig deeper into Java access modifiers and the details on how to use.

Let’s take a look at the following Java code snippet below that defines a class with a method that has protected access.

//JavaCodeDepot Sample 

package com.javacodedepot.java.tutorials;

public class JCDClass {

    protected int maxNumber;
}


In the example code below, JCDClassTwo can access the maxNumber variable directly because it is in the same package.

//JavaCodeDepot.com Sample 

package com.javacodedepot.java.tutorials;

public class JCDClassTwo {

    void calculateMax() {

        JCDClass jcdClass = new JCDClass();

        jcdClass.maxNumber = 777;  
    }
}


The sample Java code below defines a new class that tries to access the maxNumber protected variable directly, which the compiler complains about because it’s not in the same class.

//JavaCodeDepot Sample 

package com.javacodedepot.java.tutorials.util;

import com.javacodedepot.java.tutorials.JCDClass;

public class JCDUtility {

    void calculateMax() {

        JCDClass jcdClass = new JCDClass();

        jcdClass.maxNumber = 777; 
    }
}


The complete list of Java reserved keywords contains a total of 50 keywords and 3 literal words that are unable to be used as variable names.

Add a Comment

Your email address will not be published. Required fields are marked *