CodeGym/Java Blog/Keywords in Java/Java protected keyword
Author
Aditi Nawghare
Software Engineer at Siemens

Java protected keyword

Published in the Keywords in Java group
members
In Java, access modifiers control the visibility of classes, methods, and variables. "Protected" is one of these modifiers that restricts the accessibility of a class member. It is only visible to its own class, subclasses, and classes in the same package. It plays a crucial role in writing efficient and secure Java code.

Java protected keyword

The "protected" keyword in Java is an access modifier used to restrict the visibility of a class, method, or variable. When a class member is marked as protected, it can be accessed by the members of its own class, its subclasses, and classes in the same package. However, it cannot be accessed by any class outside the package.

Protected Class

Java also allows us to declare a protected class. A protected class is only accessible to its subclasses and classes in the same package. The keyword protected can be used with the class keyword to define a protected class.
protected class MyProtectedClass {
   // code here
}

Implementation of protected keywords in Java

Let's take a look at a simple example that demonstrates the implementation of the protected keyword in Java:
class A {
   protected int x = 10;
}

class B extends A {
   void display() {
      System.out.println("The value of x is: " + x);
   }
}

class Main {
   public static void main(String[] args) {
      B obj = new B();
      obj.display();
   }
}
In the above code, we have two classes A and B. Class A has a protected variable named x. The class B extends class A and has a method named display, which simply prints the value of x. In the main method, we create an object of class B and call the display method. The output of the above code will be:
The value of x is: 10
Since the variable x is marked as protected in class A, it is accessible in class B, which extends class A.

Test Exercise

Try declaring a “public” class and use class A or B there. Test if you can access their data variables. Java protected keyword - 1

Conclusion

The protected keyword in Java is an important access modifier that provides limited access to class members. When used properly, it can help to keep the code secure and organized. It is worth noting that the protected keyword is not often used in practice, but it is essential to know its implementation and usage to write efficient and secure Java code.
Comments
  • Popular
  • New
  • Old
You must be signed in to leave a comment
This page doesn't have any comments yet