// Parent class demonstrating encapsulation
class EncapsulationDemo {
// Private variable accessible only within this class
private int privateVariable;
// Public method to set the private variable
public void setPrivateVariable(int value) {
// Encapsulation: controlling access to private variable through a public method
this.privateVariable = value;
}
// Public method to get the private variable
public int getPrivateVariable() {
return this.privateVariable;
}
// Protected method accessible within this class and subclasses
protected void protectedMethod() {
System.
out.
println("This is a protected method."); }
}
// Subclass demonstrating inheritance and access to protected members
class SubClass extends EncapsulationDemo {
// Public method in subclass accessing protected method of parent class
public void accessProtectedMethod() {
protectedMethod(); // Accessing protected method of parent class
}
}
// Main class to demonstrate the encapsulation
public class Main {
public static void main
(String[] args
) { // Creating an instance of EncapsulationDemo class
EncapsulationDemo obj = new EncapsulationDemo();
// Setting the private variable using a public method
obj.setPrivateVariable(10);
// Getting the private variable using a public method
int value = obj.getPrivateVariable();
System.
out.
println("Private variable: " + value
);
// Creating an instance of SubClass
SubClass subObj = new SubClass();
// Accessing the protected method of the parent class through subclass
subObj.accessProtectedMethod();
}
}