🌟 Join our Telegram group for exclusive updates! Join Now Get Involved

Encapsulation

Encapsulation in Java

Encapsulation is one of the four fundamental principles of Object-Oriented Programming (OOP), along with inheritance, polymorphism, and abstraction. It refers to the bundling of data (attributes or fields) and methods (functions) that operate on the data within a single unit called a class. Encapsulation helps in hiding the internal details of an object and exposing only what is necessary for the outside world. This concept is crucial for achieving data integrity, security, and code organization.

Key Concepts of Encapsulation:

  1. Data Hiding:
    • Attributes of a class are typically declared with private access modifiers to restrict direct access from outside the class.
    • Access to these attributes is provided through getter and setter methods, allowing controlled access and modification.
    public class Person {
        // Private attribute
        private String name;
    
        // Getter method
        public String getName() {
            return name;
        }
    
        // Setter method
        public void setName(String name) {
            this.name = name;
        }
    }
  2. Access Modifiers:
    • Java provides access modifiers (private, protected, default, and public) to control the visibility of members (fields, methods, and inner classes) in a class.
    • Private members are accessible only within the same class, promoting data encapsulation.
  3. Getters and Setters:
    • Getter methods retrieve the values of private attributes.
    • Setter methods modify the values of private attributes.
    • This allows controlled access to the internal state of an object.
    public class BankAccount {
        private double balance;
    
        // Getter
        public double getBalance() {
            return balance;
        }
    
        // Setter
        public void setBalance(double balance) {
            if (balance >= 0) {
                this.balance = balance;
            } else {
                System.out.println("Invalid balance");
            }
        }
    }
  4. Immutable Classes:
    • An immutable class is a class whose instances cannot be modified after they are created.
    • It achieves encapsulation by ensuring that the state of an object cannot be changed once it is set.
    public final class ImmutablePerson {
        private final String name;
    
        public ImmutablePerson(String name) {
            this.name = name;
        }
    
        public String getName() {
            return name;
        }
    }

Benefits of Encapsulation:

  • Data Integrity: Encapsulation helps maintain the integrity of data by controlling access and modification through methods.
  • Security: Private members are not directly accessible, enhancing security and preventing unintended interference.
  • Code Organization: Encapsulation organizes code by grouping related data and behaviors into classes, making the codebase more manageable.
  • Flexibility: It allows for changes to the internal implementation of a class without affecting the external code that uses the class.

Encapsulation Example:

public class Circle {
    private double radius;

    public Circle(double radius) {
        setRadius(radius);
    }

    public double getRadius() {
        return radius;
    }

    public void setRadius(double radius) {
        if (radius > 0) {
            this.radius = radius;
        } else {
            System.out.println("Invalid radius");
        }
    }

    public double calculateArea() {
        return Math.PI * Math.pow(radius, 2);
    }
}

In this example, the Circle class encapsulates the radius attribute with private access. Getter and setter methods provide controlled access to the radius, ensuring that it remains a valid value. The calculateArea method operates on the encapsulated data to compute the area of the circle.

Encapsulation is a fundamental principle that promotes good software design practices, such as information hiding and modularization, leading to more maintainable and scalable code.

Cookies Consent

This website uses cookies to ensure you get the best experience on our website.

Cookies Policy

We employ the use of cookies. By accessing BYTEFOXD9, you agreed to use cookies in agreement with the BYTEFOXD9's Privacy Policy.

Most interactive websites use cookies to let us retrieve the user’s details for each visit. Cookies are used by our website to enable the functionality of certain areas to make it easier for people visiting our website. Some of our affiliate/advertising partners may also use cookies.