Categories: OOPS

Encapsulation in Java: Theory, Implementation and Best Practices

Index

What is Encapsulation in Java?

Data Hiding

Understanding Encapsulation in Java through a Real-World Analogy

The Pill Analogy

Understanding Encapsulation in Java with the help of the code.

class Human {
  int age;
  String name;
}

public class Demo {
  public static void main (String args[]) {
    Human obj = new Human();
    obj.age = 54;
    obj.name = "Ateev";
    
    System.out.println(obj.name + " is " + obj.age + " years old");
  }
}

Output

class Human {
  private int age;
  private String name;
}

public class Demo {
  public static void main (String args[]) {
    Human obj = new Human();
    obj.age = 54;
    obj.name = "Ateev";
    
    System.out.println(obj.name + " is " + obj.age + " years old");
  }
}

Output

class Human {
  private int age;
  private String name;
  
  public int getAge() {
    return age;
  }
  
  public String getName() {
    return name;
  }
}

public class Demo {
  public static void main (String args[]) {
    Human obj = new Human();
    obj.age = 54;
    obj.name = "Ateev";
    
    System.out.println(obj.name + " is " + obj.age + " years old");
  }
}

Output

class Human {
    private int age;
    private String name;
    
    public int getAge() {
        return age;
    }
    
    public String getName() {
        return name;
    }
}

public class Demo {
    public static void main(String args[]) {
        Human obj = new Human();
        obj.age = 54;
        obj.name = "Ateev";
        System.out.print(obj.getName() + ": " + obj.getAge());
    }
}

Output

System.out.println(obj.name + " : " + obj.age);
 System.out.println(obj.getName() + " : " + obj.getAge());
class Human {
  private int age;
  private String name;
  
  public int getAge() {
    return age;
  }
  
  public String getName() {
    return name;
  }
}

public class Demo {
  public static void main (String args[]) {
    Human obj = new Human();
    System.out.println(obj.getName() + " is " + obj.getAge() + " years old");
  }
}

Output

Declaring and initialising the variables at the same time

class Human {
  private int age = 54;
  private String name = "Ateev";
  
  public int getAge() {
    return age;
  }
  
  public String getName() {
    return name;
  }
}

public class Demo {
  public static void main (String args[]) {
    Human obj = new Human();
    System.out.println(obj.getName() + " is " + obj.getAge() + " years old");
  }
}

Output

Declaring the variables in the Human class and initialising them in the Demo class.

class Human {
    private int age;
    private String name;
    
    public int getAge() {
        return age;
    }
    
    public void setAge(int a) {
        age = a;
    }
    
    public String getName() {
        return name;
    }
    
    public void setName(String n) {
        name = n;
    }
}

public class Demo {
    public static void main(String args[]) {
        Human obj = new Human();
        obj.setAge(54);
        obj.setName("Ateev");
        System.out.print(obj.getName() + " is " + obj.getAge() + " years old");
    }
}

Output

What are Getter and Setter Public Methods in Encapsulation in Java?

class Human {
    private int age;
    private String name;
    
    public int AAA() {
        return age;
    }
    
    public void GGG(int a) {
        age = a;
    }
    
    public String BBB() {
        return name;
    }
    
    public void HHH(String n) {
        name = n;
    }
}

public class Demo {
    public static void main(String args[]) {
        Human obj = new Human();
        obj.GGG(54);
        obj.HHH("Ateev");
        System.out.print(obj.AAA() + " is " + obj.BBB() + " years old");
    }
}

Output

Why do we need Encapsulation in Java?

Data Protection

Controlled Access

Code Maintenance:

Understanding Encapsulation in Java, the professional way

class Human {
    private int age;
    private String name;

    public int getAge() { return age; }
    public void setAge(int a) { age = a; }

    public String getName() { return name; }
    public void setName(String n) { name = n; }
}
class Human {
    private final String name;
    private int age;

    public Human(String name, int age) {
        if (age < 0) {
            throw new IllegalArgumentException("Age cannot be negative");
        }
        this.name = name;
        this.age = age;
    }

    public int getAge() {
        return age;
    }

    public String getName() {
        return name;
    }
}

public class Main {
    public static void main(String[] args) {
        // Create a Human object
        Human person = new Human("Alice", 25);

        // Print initial details
        System.out.println("Name: " + person.getName());
        System.out.println("Age: " + person.getAge());
    }
}

Output

class Human {
    private String name;
    private int age;

    public Human(String name, int age) {
        if (age < 0) {
            throw new IllegalArgumentException("Age cannot be negative");
        }
        this.name = name;
        this.age = age;
    }

    public int getAge() {
        return age;
    }

    public void celebrateBirthday() {
        age++;
    }

    public String getName() {
        return name;
    }
}

public class Main {
    public static void main(String[] args) {
        // Create a Human object
        Human person = new Human("Alice", 25);

        // Print initial details
        System.out.println("Name: " + person.getName());
        System.out.println("Age: " + person.getAge());

        // Celebrate birthday
        person.celebrateBirthday();

        // Print updated age
        System.out.println("After birthday, Age: " + person.getAge());
    }
}

Output

Best practices for Encapsulation in Java

class Human {
    private int age;
    private String name;
    
    public int getAge() {
        return age;
    }
    
    public void setAge(int a) {
        age = a;
    }
    
    public String getName() {
        return name;
    }
    
    public void setName(String n) {
        name = n;
    }
}

public class Demo {
    public static void main(String args[]) {
        Human obj = new Human();
        obj.setAge(54);
        obj.setName("Ateev");
        System.out.print(obj.getName() + " is " + obj.getAge() + " years old");
    }
}

Use constructors to enforce a valid object state

public class Main {

    public static void main(String[] args) {
        Human person = new Human("Ateev", 54);

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

class Human {
    private String name;
    private int age;

    public Human(String nameValue, int ageValue) {

        if (nameValue == null || nameValue.isEmpty()) {
            throw new IllegalArgumentException("Invalid name");
        }

        if (ageValue < 0) {
            throw new IllegalArgumentException("Invalid age");
        }

        name = nameValue;
        age = ageValue;
    }

    public String getName() { 
        return name; 
    }

    public int getAge() { 
        return age; 
    }
}

Output

Guarding Object Integrity

public class Main {

    public static void main(String[] args) {
        Human person = new Human("Ateev", 54);

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

class Human {
    private String name;
    private int age;

    public Human(String nameValue, int ageValue) {

        if (nameValue == null || nameValue.isEmpty()) {
            throw new IllegalArgumentException("Invalid name");
        }

        if (ageValue < 0 || ageValue > 100) {
            throw new IllegalArgumentException("Invalid age");
        }

        name = nameValue;
        age = ageValue;
    }

    public String getName() { 
        return name; 
    }

    public int getAge() { 
        return age; 
    }

    public void setAge(int value) {
        if (value < 0 || value > 100) {
            throw new IllegalArgumentException("Invalid age");
        }

        age = value;
    }
}

When the value of the age variable is less than 0

When the value of the age variable is more than 100

Using Encapsulation in Java to reduce coupling

class Human {

    private int age;
    private String name;

    public Human(String n, int a) {

        if (n == null || n.trim().isEmpty()) {
            throw new IllegalArgumentException("Name cannot be empty");
        }

        if (a < 0 || a > 130) {
            throw new IllegalArgumentException("Age must be between 0 and 130");
        }

        name = n;
        age = a;
    }

    public String introduce() {
        return name + " is " + age + " years old";
    }
}

public class Demo {

    public static void main(String[] args) {

        Human person = new Human("Ateev", 54);
        System.out.println(person.introduce());
    }
}

Output

class Human {

    private int age;

    private String name;

    public Human(String n, int a) {

        setName(n);

        setAge(a);

    }

    public String introduce() {

        return name + " is " + age + " years old";

    }

    public void setName(String n) {

        if (n == null || n.trim().isEmpty()) {

            throw new IllegalArgumentException("Name cannot be empty");

        }

        name = n;

    }

    public void setAge(int a) {

        if (a < 0 || a > 130) {

            throw new IllegalArgumentException("Age must be between 0 and 130");

        }

        age = a;

    }

}

public class Demo {

    public static void main(String[] args) {

        Human person = new Human("Ateev", 54);

        System.out.println(person.introduce());

        person.setName("Tarun");

        person.setAge(32);

        System.out.println(person.introduce());

    }

}

Output

Conclusion

Frequently Asked Question

Q1. What is the difference between encapsulation and abstraction?
Q2. What happens if we don’t use encapsulation in a Java program?

Ans. Without encapsulation, data can be easily accessed or modified from outside the class, leading to security risks, less control over data, and potential errors that are harder to trace.

Q3. Is it possible to encapsulate a method in Java?
Q4. What are the design patterns that heavily rely on encapsulation?
Q5. Is it possible to overuse the Getter and Setter methods?

Having getters and setters does not break encapsulation; what breaks encapsulation is automatically adding a getter and a setter for every data member (every field, in Java lingo), without giving it any thought. While this is better than making all data members public, it is only a small step away

Ateev Duggal

I am Ateev Duggal, a front-end web developer, and a blogger. I write blogs mainly on React JS and have an experience of over 1.5 years of freelancing. I have worked on both static and dynamic projects again using React JS like a table to show clients data which was fetched using API, a review slider, pagination component, etc, and many websites like Parent, landing pages for Ataota, and many more. Some of my blogs have been published on freecodecamp, dev.to, Medium, geeks for geeks, and many other blogging platforms and developer's communities. My Primary skills not only include React JS but HTML5, CSS3, JS, Jquery, Git, and Bootstrap also. You can visit my GitHub Profile and LinkedIn profile for more information about me or you can visit my Website at tekolio.com

Recent Posts

What is Inheritance in Java and why is it important?

Inheritance in Java is a mechanism of creating a new class or interface from an…

8 months ago

Understanding the Fundamentals of OOPS in Java

In this blog, we will not only understand the concepts of OOPS in Java in…

9 months ago

OOPS Concepts 101: What Are the Key Concepts You Need to Know?

Object-Oriented Programming System (OOPS) is a programming paradigm built around the concept of objects —…

10 months ago

What is abstraction in Java and how to achieve it?

Abstraction in Java is one of the four pillars of OOPs which is used to…

2 years ago

How to Detect a Click Outside of a React Component using Hooks?

In this blog, we will learn How to Detect a Click Outside of a React…

3 years ago

How to Implement Infinite Scrolling in React by Making a Custom Hook

learn How to Use Hooks to Create Infinite Scrolling in React by making a custom…

3 years ago