Encapsulation in Java Classes

Encapsulation in Java Classes

Hello! In this lesson, we're revisiting Encapsulation, Private Attributes, and Private Methods in Object-Oriented Programming (OOP). Think of encapsulation as an invisible fence that safeguards your garden (the class) from outside interference, keeping data and methods secure inside. Within this garden, certain elements (Private Attributes and Methods) are only accessible to the gardener, providing an extra layer of protection and ensuring data integrity in your classes!

Encapsulation Explained

Encapsulation is a fundamental concept in Object-Oriented Programming (OOP) that involves bundling data (attributes) and methods (functions) that operate on the data into a single unit, called a class. This concept also limits direct access to some of an object's components, preventing accidental interference and misuse of the data. For instance, in a multiplayer game, you might create a Player class that encapsulates data (health, armor, stamina) and methods (receiveDamage, shieldHit, restoreHealth).

class Player {
    private int health;
    private int armor;
    private int stamina;

    public Player(int health, int armor, int stamina) {
        this.health = health;
        this.armor = armor;
        this.stamina = stamina;
    }

    public void receiveDamage(int damage) {
        health -= damage;  // Reduce health
    }
    
    public void shieldHit(int armorDamage) {
        armor -= armorDamage;  // Decrease armor
    }

    public void restoreHealth(int healthIncrease) {
        health += healthIncrease;  // Restore health
    }

    public void displayStatus() {
        System.out.println("Health: " + health + ", Armor: " + armor + ", Stamina: " + stamina);
    }
}

public class Solution {
    public static void main(String[] args) {
        Player player = new Player(100, 50, 77);
        player.displayStatus();  // Outputs: Health: 100, Armor: 50, Stamina: 77
    }
}

In Java, player is an instance of the Player class on which you can call methods.

Private Attributes

In Java, the private keyword is used to designate attributes and methods as accessible only within their own class. This ensures the integrity of an object by restricting direct external access and interference.

Private Attributes, such as balance in a BankAccount class, ensure the integrity and security of data by restricting modifications to the methods within the class and disallowing direct external access.

class BankAccount {
    private double balance; // Declare a private field

    // Constructor to initialize the balance
    public BankAccount(double balance) {
        this.balance = balance; // Initialize the private attribute
    }

    // Method to deposit money into the account
    public void deposit(double amount) {
        balance += amount; // Deposit money
    }

    // Getter for balance
    public double getBalance() {
        return balance; // A public method to access balance
    }

    // Optional setter for balance with validation
    public void setBalance(double balance) {
        if (balance >= 0) {
            this.balance = balance;
        } else {
            System.out.println("Balance cannot be negative.");
        }
    }
}

public class Solution {
    public static void main(String[] args) {
        BankAccount bankAccount = new BankAccount(100); // Initialize account with balance of 100
        bankAccount.setBalance(200); // Works: sets balance to 200
        System.out.println(bankAccount.getBalance()); // Works: logs 200
        bankAccount.setBalance(-50); // Logs: "Balance cannot be negative."
    }
}
Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal