Share

Encapsulation in Java (The Easy Way)

Home » Programming Language » Java » Encapsulation in Java (The Easy Way)
encapsulation in java the easy way
encapsulation in java the easy way

Java is a popular programming language used to build software applications. In Java, encapsulation is an important concept that helps developers write better code. But what exactly is encapsulation, and how does it work? In this article, we’ll explain encapsulation in Java in detail, using simple language that even a five-year-old can understand. We’ll cover the following topics:

  1. What is encapsulation?
  2. Why is encapsulation important?
  3. How does encapsulation work in Java?
  4. Examples of encapsulation in Java

So let’s get started.

1. What is encapsulation?

Encapsulation is a big word that simply means “to protect something inside a box”. Think of a toy box. You put all your toys inside the box and close the lid. The box is like a protective layer around your toys. Nobody can touch your toys without opening the box first.

In programming, encapsulation is similar. You put data (like numbers, words, or even other pieces of code) inside a box, or “object”. The object is like a protective layer around your data. Nobody can access your data without going through the object first.

2. Why is encapsulation important?

Encapsulation is important for two reasons: security and simplicity.

Security

Imagine you have a secret code that you don’t want anyone else to see. You could write the code in your program, but then anyone who looks at the code can see it too. That’s not very secure! But if you put the code inside an object and only give certain parts of the program permission to access the object, then nobody else can see the code. That’s much more secure!

Simplicity

When you write a program, you want it to be easy to read and understand. But if you put all your code in one big pile, it can be hard to know what’s going on. Encapsulation helps by separating your code into smaller, easier-to-understand pieces. Each object contains only the code that’s related to it, making it easier for you (and other developers) to read and understand.

3. How does encapsulation work in Java?

In Java, encapsulation is achieved through the use of classes and objects. A class is like a blueprint for an object. It describes what kind of data the object will hold and what it can do with that data.

For example, let’s say we want to create a program to keep track of a person’s name, age, and favorite color. We could create a class called “Person” that looks like this:

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

    // constructor
    public Person(String name, int age, String favoriteColor) {
        this.name = name;
        this.age = age;
        this.favoriteColor = favoriteColor;
    }

    // getters and setters
    public String getName() {
        return name;
    }

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

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getFavoriteColor() {
        return favoriteColor;
    }

    public void setFavoriteColor(String favoriteColor) {
        this.favoriteColor = favoriteColor;
    }
}

This class has three private variables: name, age, and favoriteColor. These variables are marked as private, which means they can only be accessed from within the class. This is the first step in encapsulation – protecting our data from outside access.

The class also has a constructor, which is a special method that gets called when we create an object of the class. The constructor takes three parameters (name, age, and favoriteColor) and assigns them to the private variables. This is how we set the initial values for our data.

Finally, the class has getter and setter methods for each variable. These methods allow other parts of the program to access and modify the private variables. However, they do so in a controlled way – the methods can enforce rules or restrictions on how the data is accessed or modified. For example, we might want to make sure that the age variable is never negative, so we can put a check in the setAge() method to prevent that from happening.

Now let’s see encapsulation in action.

4. Examples of encapsulation in Java

Let’s look at couple of examples to see encapsulation in action.

Example 1: Bank Account

Suppose we want to create a program to manage bank accounts. We could create a class called “BankAccount” that looks like this:

public class BankAccount {
   private String accountNumber;
   private double balance;

   // constructor
   public BankAccount(String accountNumber) {
      this.accountNumber = accountNumber;
      this.balance = 0.0;
   }

   // getters and setters
   public String getAccountNumber() {
      return accountNumber;
   }

   public double getBalance() {
      return balance;
   }

   // methods
   public void deposit(double amount) {
      balance += amount;
   }

   public void withdraw(double amount) {
      balance -= amount;
   }
}

This class has two private variables: accountNumber and balance. We don’t want anyone outside the class to be able to access or modify these variables directly – that’s why they’re private. Instead, we provide getter and setter methods for accountNumber and a getter method for balance. This allows other parts of the program to get information about the account (like the account number and balance), but not to change it directly.

We also have two methods – deposit() and withdraw() – that allow us to modify the balance. However, we do so in a controlled way – we can make sure that the balance never goes below zero, for example.

Example 2: Car

Now let’s se other example, suppose we want to create a program to manage cars. We could create a class called “Car” that looks like this:

public class Car {
   private String make;
   private String model;
   private int year;
   private double speed;

   // constructor
   public Car(String make, String model, int year) {
      this.make = make;
      this.model = model;
      this.year = year;
      this.speed = 0.0;
   }

   // getters and setters
   public String getMake() {
      return make;
   }

   public String getModel() {
      return model;
   }

   public int getYear() {
      return year;
   }

   public double getSpeed() {
      return speed;
   }

   // methods
   public void accelerate(double amount) {
      speed += amount;
   }

   public void brake(double amount) {
      speed -= amount;
      if (speed < 0.0) {
         speed = 0.0;
      }
   }
}

This class has four private variables: make, model, year, and speed. We provide getter methods for each variable same as we did for example 1, but no setter methods – we don’t want anyone outside the class to be able to change the make, model, or year of the car.

We do provide two methods – accelerate() and brake() – that allow us to modify the speed of the car. However, we do so in a controlled way – we make sure that the speed never goes below zero.

Conclusion

Encapsulation is a fundamental concept in object-oriented programming, and it allows us to create more robust and secure programs. By encapsulating data within a class and providing controlled access to that data through getter and setter methods, we can ensure that our program behaves correctly even if other parts of the program try to misuse or modify the data in unintended ways.

In Java, encapsulation is achieved through the use of private variables and public getter and setter methods. By marking variables as private, we prevent other parts of the program from accessing or modifying them directly. Getter and setter methods provide controlled access to the variables, allowing other parts of the program to get or modify the data, but enforcing any rules or restrictions we’ve put in place.

Overall, encapsulation is a powerful tool that can help us write better code, and it’s an essential concept for anyone learning Java or object-oriented programming.

your comments are appreciated and if you wants to see your articles on this platform then please shoot a mail at this address kusingh@programmingeeksclub.com

Thanks for reading 🙂

Join Our Newsletter!

Join our newsletter to get our latest ebook "Ultimate JavaScript Cheat-Sheet", and Tips, Articles..

We don’t spam! Read our privacy policy for more info.

Join Our Newsletter!

Join our newsletter to get our latest ebook "Ultimate JavaScript Cheat-Sheet", and Tips, Articles..

We don’t spam! Read our privacy policy for more info.