Encapsulation in Java

Encapsulation

Introduction To Encapsulation

Encapsulation is the process of hiding the internal details of an object from the outside world.It is one of the fundamental concepts of object-oriented programming and is aimed at making the program more robust and secure.

Encapsulation helps to prevent the accidental modification of data by restricting access to the internal state of an object.

In this article, we will discuss what is encapsulation, how it works in Java, and some examples of its implementation.

Understanding Encapsulation in Java

In Java, encapsulation is achieved through the use of access modifiers. Access modifiers are keywords that determine the visibility of a class, method, or variable. Java provides four types of access modifiers:

  • Public: The public access modifier allows a class, method, or variable to be accessed from any other class in the same or different package.
  • Private: The private access modifier restricts access to the class members within the same class.
  • Protected: The protected access modifier allows a class member to be accessed within the same class and its subclasses.
  • Default: If no access modifier is specified, the default access modifier is used. It allows access to class members within the same package.
  • Security: Encapsulation provides a level of security by preventing unauthorized access to the internal state of an object.
  • Modularity: Encapsulation allows the programmer to break down a complex program into smaller, more manageable modules.
  • Flexibility: Encapsulation provides flexibility by allowing the programmer to change the internal implementation of a class without affecting other parts of the program.
  • Code Reusability: Encapsulation helps to improve code reusability by promoting the use of classes and objects.

Encapsulation vs. Abstraction

Encapsulation and abstraction are two important concepts in object-oriented programming. While encapsulation is concerned with hiding the internal details of an object, abstraction is concerned with hiding the implementation details of a class.

Encapsulation provides data hiding, while abstraction provides a way to represent complex systems in a simplified way. Encapsulation and abstraction work hand in hand to create well-designed object-oriented programs.

Advantages of Encapsulation in Java

Encapsulation

Access Modifiers in Java 

MethodsDescription
Public:Visible to all classes
Protected:Visible to the class and its subclasses
Default:Visible to the class and its package
private:Visible only to the class

Common Mistakes in Encapsulation

Although encapsulation is an important concept in Java programming, it is often misunderstood and implemented incorrectly.

  • Here are some common mistakes that programmers make when implementing encapsulation:
    • Overusing getter and setter methods: Some programmers tend to overuse getter and setter methods, which can lead to excessive code bloat and decreased performance.
    • Exposing too much information: It is important to only expose the necessary information through getter and setter methods. Exposing too much information can lead to security vulnerabilities.
    • Using public fields: Using public fields can lead to security vulnerabilities and can make it difficult to modify the code in the future.

Example 1:Encapsulation In Java

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

    // Getter methods
    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }

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

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

public class Main {
    public static void main(String[] args) {
        Person person = new Person();

        // Set the name and age using the setter methods
        person.setName("John");
        person.setAge(30);

        // Get the name and age using the getter methods
        String name = person.getName();
        int age = person.getAge();

        System.out.println("Name: " + name);
        System.out.println("Age: " + age);
    }
}

Output

Name: John
Age: 30

Example 2: Encapsulation in Java

Run
class BankAccount {
    private int accountNumber;
    private String accountHolderName;
    private double accountBalance;

    public BankAccount(int accountNumber, String accountHolderName, double accountBalance) {
        this.accountNumber = accountNumber;
        this.accountHolderName = accountHolderName;
        this.accountBalance = accountBalance;
    }

    // Getter methods
    public int getAccountNumber() {
        return accountNumber;
    }

    public String getAccountHolderName() {
        return accountHolderName;
    }

    public double getAccountBalance() {
        return accountBalance;
    }

    // Setter methods
    public void setAccountNumber(int accountNumber) {
        this.accountNumber = accountNumber;
    }

    public void setAccountHolderName(String accountHolderName) {
        this.accountHolderName = accountHolderName;
    }

    public void setAccountBalance(double accountBalance) {
        this.accountBalance = accountBalance;
    }
}

public class Main {
    public static void main(String[] args) {
        BankAccount account = new BankAccount(12345, "Kumar Ayush", 1000.0);

        // Get account details
        int accountNumber = account.getAccountNumber();
        String accountHolderName = account.getAccountHolderName();
        double accountBalance = account.getAccountBalance();

        System.out.println("Account Number: " + accountNumber);
        System.out.println("Account Holder Name: " + accountHolderName);
        System.out.println("Account Balance: " + accountBalance);

        // Update account balance
        account.setAccountBalance(1500.0);
        accountBalance = account.getAccountBalance();
        System.out.println("New Account Balance: " + accountBalance);
    }
}

Output

Account Number: 12345
Account Holder Name: Kumar Ayush
Account Balance: 1000.0
New Account Balance: 1500.0

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

Question 1. What is the difference between encapsulation and abstraction?

Encapsulation is concerned with hiding the internal details of an object, while abstraction is concerned with hiding the implementation details of a class.

Question 2. What are access modifiers in Java?

Access modifiers are keywords that determine the visibility of a class, method, or variable in Java.

Question 3. Why is encapsulation important in Java?

Encapsulation is important in Java because it provides a level of security, promotes modularity and flexibility, and improves code reusability.

Question 4. What are some common mistakes when implementing encapsulation?

Some common mistakes include overusing getter and setter methods, exposing too much information, ignoring access modifiers, mixing business logic with data, and using public fields.

Get over 200+ course One Subscription

Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others

Checkout list of all the video courses in PrepInsta Prime Subscription

Checkout list of all the video courses in PrepInsta Prime Subscription