fork download
  1. // Parent class demonstrating encapsulation
  2. class EncapsulationDemo {
  3. // Private variable accessible only within this class
  4. private int privateVariable;
  5.  
  6. // Public method to set the private variable
  7. public void setPrivateVariable(int value) {
  8. // Encapsulation: controlling access to private variable through a public method
  9. this.privateVariable = value;
  10. }
  11.  
  12. // Public method to get the private variable
  13. public int getPrivateVariable() {
  14. return this.privateVariable;
  15. }
  16.  
  17. // Protected method accessible within this class and subclasses
  18. protected void protectedMethod() {
  19. System.out.println("This is a protected method.");
  20. }
  21. }
  22.  
  23. // Subclass demonstrating inheritance and access to protected members
  24. class SubClass extends EncapsulationDemo {
  25. // Public method in subclass accessing protected method of parent class
  26. public void accessProtectedMethod() {
  27. protectedMethod(); // Accessing protected method of parent class
  28. }
  29. }
  30.  
  31. // Main class to demonstrate the encapsulation
  32. public class Main {
  33. public static void main(String[] args) {
  34. // Creating an instance of EncapsulationDemo class
  35. EncapsulationDemo obj = new EncapsulationDemo();
  36.  
  37. // Setting the private variable using a public method
  38. obj.setPrivateVariable(10);
  39.  
  40. // Getting the private variable using a public method
  41. int value = obj.getPrivateVariable();
  42. System.out.println("Private variable: " + value);
  43.  
  44. // Creating an instance of SubClass
  45. SubClass subObj = new SubClass();
  46.  
  47. // Accessing the protected method of the parent class through subclass
  48. subObj.accessProtectedMethod();
  49. }
  50. }
  51.  
Success #stdin #stdout 0.11s 55604KB
stdin
Standard input is empty
stdout
Private variable: 10
This is a protected method.