Tightly Encapsulated Class

Tightly Encapsulated Class

A tightly encapsulated class is a class that follows the principles of encapsulation to ensure data integrity and controlled access to its internal state. It encapsulates its data by declaring them as private and provides controlled access through getter and setter methods.

Here's an example of a tightly encapsulated class called "Person" with private data members (name and age) and getter/setter methods:

    
      public class Person {
          private String name;
          private int age;

          public String getName() {
              return name;
          }

          public void setName(String name) {
              this.name = name;
          }

          public int getAge() {
              return age;
          }

          public void setAge(int age) {
              if (age >= 0) {
                  this.age = age;
              } else {
                  System.out.println("Invalid age value.");
              }
          }
      }

      public class Main {
          public static void main(String[] args) {
              Person person = new Person();
              person.setName("John Doe");
              person.setAge(25);

              System.out.println("Name: " + person.getName());
              System.out.println("Age: " + person.getAge());
          }
      }
    
  
      Name: John Doe
      Age: 25
    

In this example, the "Person" class encapsulates its data members "name" and "age" by declaring them as private. It provides getter and setter methods to access and modify these private members. The setter for "age" performs validation to ensure that the age value is valid (non-negative). The "Main" class demonstrates the usage of the tightly encapsulated "Person" class by setting values using the setter methods and retrieving the values using the getter methods. The output shows the retrieved values.

Go To Encapsulation Page Click Here

Go To OOPS Page Click Here

Post a Comment

Previous Post Next Post