Java - OOP - Modifiers - Protected
Java provides access modifiers to control the visibility and accessibility of class members like fields, methods, and constructors. 'protected' is one of the four access modifiers in Java, which allows the class members to be accessed within the same package as well as subclasses outside the package.
protected data_type variable_name;
protected void method_name(){ //method body }
Here is an example of how to use the 'protected' modifier:
package examplePackage;
public class ExampleClass {
protected int num1 = 10;
protected void display() {
System.out.println("This is a protected method.");
}
}
public class SubClass extends ExampleClass {
void accessProtectedMembers() {
System.out.println("Accessing protected member num1: " + num1);
display();
}
}
In this example, we have a class named 'ExampleClass', which has a protected member variable named 'num1' and a protected method named 'display()'. We also have a subclass named 'SubClass', which extends the 'ExampleClass' and can access the protected members of the parent class.
In the 'SubClass' class, we have a method named 'accessProtectedMembers()' which can access the protected members of 'ExampleClass' using the 'super' keyword. We are able to access the protected variable 'num1' and call the protected method 'display()' in the 'SubClass'.
That's the basic idea of using the 'protected' modifier in Java. It is useful when you want to make members accessible within the same package as well as the subclasses outside the package.