Java Encapsulation

Hello there, fellow Java enthusiasts! Today, we’re diving into the world of Java Encapsulation. Ready to encapsulate your mind around this concept? Let’s get started!

Introduction

Java Encapsulation is one of the four fundamental OOP concepts. The other three are inheritance, polymorphism, and abstraction. But today, we’re focusing on encapsulation. Why? Because it’s the Java way of bundling up variables and methods together within a single unit, a.k.a. a class.

Understanding Java Encapsulation

Encapsulation is like a protective shell that prevents code and data from being arbitrarily accessed by other code defined outside the shell. Think of it as a capsule (hence the name!). Inside this capsule, we have our data and methods, safe and sound from the outside world.

In the context of object-oriented programming, encapsulation is all about combining variables and methods into a single unit, known as a class. This approach helps to achieve data hiding, as the data of a class is hidden from other classes, and can only be accessed through the methods of their current class.

Java Encapsulation with Examples

Let’s take a look at how encapsulation works in Java with a simple example. Consider a class named Employee, which has three fields: name, idNum, and age. We can encapsulate these fields by declaring them as private and providing public getter and setter methods to modify and view the variables’ values.

public class Employee {
   private String name;
   private String idNum;
   private int age;

   public int getAge() {
      return age;
   }

   public String getName() {
      return name;
   }

   public String getIdNum() {
      return idNum;
   }

   public void setAge( int newAge) {
      age = newAge;
   }

   public void setName(String newName) {
      name = newName;
   }

   public void setIdNum( String newId) {
      idNum = newId;
   }
}
Java

In the above example, name, idNum, and age are encapsulated in the Employee class. This class is fully encapsulated, as its variables are declared as private and can only be accessed via getter and setter methods.

Advantages of Java Encapsulation

Encapsulation has a lot of advantages:

  1. Control of data: By encapsulating the data, we have full control over what gets stored in the fields. We can add validation in the setter methods to protect the fields from being polluted with bad data.
  2. Increased security: Data is hidden from the outside world, and only accessible through the methods of the current class. This ensures the integrity of the data.
  3. Flexibility and maintainability: The fields can be made read-only or write-only according to our needs. If we wish to make the name read-only, we simply don’t define the setName() method.

Java Encapsulation vs Abstraction

Encapsulation and abstraction often go hand in hand in Java, but they’re not the same thing. While encapsulation is about bundling data and methods within one unit and hiding the data from the outside world, abstraction is about hiding the complexity and only showing the essential features of the object.

In other words, encapsulation is more focused on the implementation, hiding the details on how the object works. On the other hand, abstraction is more about the interface, hiding how the action is performed and showing only the necessary information.

Java Encapsulation Examples

Here are two complete code examples demonstrating Java Encapsulation:

Example 1:

public class Student {
   private String name;
   private int rollNo;

   public String getName() {
      return name;
   }

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

   public int getRollNo() {
      return rollNo;
   }

   public void setRollNo(int rollNo) {
      this.rollNo = rollNo;
   }
}

public class Test {
   public static void main(String[] args) {
      Student s = new Student();
      s.setName("John");
      s.setRollNo(2);
      System.out.println("Name: " + s.getName());
      System.out.println("Roll No: " + s.getRollNo());
   }
}
Java

In this example, we have a Student class with two private fields: name and rollNo. We’re using getter and setter methods to access these fields. The Test class demonstrates how to use these methods.

Output:

Name: John
Roll No: 2

In this example, we created a Student object named s. We then set the name to “John” and the rollNo to 2 using the setter methods. When we print the name and rollNo using the getter methods, we get “John” and 2 respectively.

Run the JavaCode with IntelliJ IDEA or Visual Studio Code

Create two class files such as Student.java and Test.java which would contain the respective classes. Run the code and you will see the output.

Run Java Encapsulation Example with IntelliJ IDEA
Run Java Encapsulation Example with IntelliJ IDEA
Run Java Encapsulation Example with Visual Studio Code
Run Java Encapsulation Example with IntelliJ IDEA

Example 2:

public class Bank {
   private double balance;

   public double getBalance() {
      return balance;
   }

   public void deposit(double amount) {
      if(amount > 0) {
         balance += amount;
      }
   }

   public void withdraw(double amount) {
      if(amount > 0 && balance >= amount) {
         balance -= amount;
      }
   }
}

public class Test {
   public static void main(String[] args) {
      Bank myBank = new Bank();
      myBank.deposit(2000);
      myBank.withdraw(500);
      System.out.println("Balance: " + myBank.getBalance());
   }
}
Java

In this example, we have a Bank class with a private field balance. We’re using a getter method and two other methods deposit and withdraw to manipulate the balance. The Test class demonstrates how to use these methods.

Output

Balance: 1500.0

In this example, we created a Bank object named myBank. We then deposited 2000 into the account and withdrew 500 from it. When we print the balance, we get 1500.0.

Wrapping Up

Java Encapsulation is a fundamental concept in object-oriented programming. It helps us to bundle data and methods within a single unit and hide the data from the outside world. Understanding encapsulation is crucial for any Java developer, as it forms the basis for more advanced concepts and helps to write secure and maintainable code.

Java Encapsulation Interview Questions (FAQ)

  • What is encapsulation in Java?

    Encapsulation in Java is one of the four fundamental principles of Object-Oriented Programming (OOP). It’s a protective mechanism that allows us to hide the data from outside interference and misuse. In Java, encapsulation is achieved by declaring the variables as private and providing public setter and getter methods to modify and view the variables’ values.

  • How is encapsulation achieved in Java?

    In Java, encapsulation is achieved by declaring the variables of a class as private and providing public setter and getter methods to modify and view the variables’ values. The private variables are hidden from other classes, and can only be accessed through the methods of their current class.

  • What are the advantages of encapsulation in Java?

    Encapsulation has several advantages in Java. It helps to control the data by providing setter and getter methods, increases security by hiding the data, and enhances maintainability and flexibility of the code. It’s a fundamental concept of OOP and forms the basis for more advanced concepts in Java.

  • How does encapsulation relate to other OOP concepts in Java?

    Encapsulation is one of the four fundamental principles of OOP in Java, along with inheritance, polymorphism, and abstraction. While encapsulation is about hiding the details and protecting data from outside interference, inheritance is about deriving new classes from existing ones, polymorphism is about using a single interface to represent different types, and abstraction is about hiding the complexity and only showing the essential features of the object.

  • Can you provide an example of encapsulation in Java?

    Sure, here’s a simple example of encapsulation in Java:

public class Employee {
   private String name;
   private String idNum;
   private int age;

   public int getAge() {
      return age;
   }

   public String getName() {
      return name;
   }

   public String getIdNum() {
      return idNum;
   }

   public void setAge( int newAge) {
      age = newAge;
   }

   public void setName(String newName) {
      name = newName;
   }

   public void setIdNum( String newId) {
      idNum = newId;
   }
}
Java

In this example, name, idNum, and age are encapsulated in the Employee class. This class is fully encapsulated, as its variables are declared as private and can only be accessed via getter and setter methods.

  • What is a real-life example of encapsulation in Java?

    A real-life example of encapsulation is a capsule. Inside a capsule, the drug (data) is encapsulated, and outside the capsule is the shell that hides the drug from the outside world. Similarly, in Java, data is encapsulated within classes using methods.

  • How do you explain encapsulation in an interview?

    Encapsulation is one of the four fundamental principles of Object-Oriented Programming (OOP). It’s a protective mechanism that allows us to hide the data from outside interference and misuse. In Java, encapsulation is achieved by declaring the variables as private and providing public setter and getter methods to modify and view the variables’ values.

  • Is it true to use encapsulation in Java?

    Yes, it’s true and highly recommended to use encapsulation in Java. Encapsulation provides control over the data and keeps the data and the codes safe from external interference. It increases the reusability of the code and makes the code easier to maintain.

  • What is the difference between encapsulation and abstraction in Java?

    While both encapsulation and abstraction are fundamental principles of OOP in Java, they serve different purposes. Encapsulation is about hiding the details and protecting data from outside interference; it’s more about data. On the other hand, abstraction is about hiding the complexity and only showing the essential features of the object; it’s more about the interface.

  • Why is encapsulation important in Java?

    Encapsulation is important in Java for several reasons. It helps to control the data by providing setter and getter methods, increases security by hiding the data, and enhances maintainability and flexibility of the code. It’s a fundamental concept of OOP and forms the basis for more advanced concepts in Java.

  1. Java Abstraction: A Comprehensive Guide
  2. Understanding Java Inheritance
  3. Java Polymorphism Explained
  4. Mastering Java Classes and Objects

That’s all, folks! I hope you found this tutorial helpful. Keep practicing and happy coding!

Scroll to Top