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.
GO TO FULL VERSION