Java Encapsulation Example

Encapsulation refers to combining data and associated functions as a single unit. In OOP, data and functions operating on that data are combined together to form a single unit, which is referred to as a class.

In Java, encapsulation is implemented via the access modifiers - public, private, and protected.

Java Encapsulation Example

Let's consider an example: a Cat class can have its state represented by fields such as moodhungry and energy. While the code external to the Cat class cannot modify any of these fields directly, it can call public methods play()feed(), and sleep() that modify the Cat state internally.
The Cat class may also have private methods that are not accessible outside the class, such as meow(). This is encapsulation.
public class Cat {

    private int mood = 50;
    private int hungry = 50;
    private int energy = 50;

    public void sleep() {
        System.out.println("Sleep ...");
        energy++;
        hungry++;
    }

    public void play() {
        System.out.println("Play ...");
        mood++;
        energy--;
        meow();
    }

    public void feed() {
        System.out.println("Feed ...");
        hungry--;
        mood++;
        meow();
    }

    private void meow() {
        System.out.println("Meow!");
    }

    public int getMood() {
        return mood;
    }

    public int getHungry() {
        return hungry;
    }

    public int getEnergy() {
        return energy;
    }
}

The only way to modify the state (private fields) is via the public methods play()feed(), and sleep(), as in the following example:

public class Main {

    public static void main(String[] args) {

        Cat cat = new Cat();
        
        cat.feed();
        cat.play();
        cat.feed();
        cat.sleep();
        
        System.out.println("Energy: " + cat.getEnergy());
        System.out.println("Mood: " + cat.getMood());
        System.out.println("Hungry: " + cat.getHungry());
    }
}
The output will be as follows:

Feed ...
Meow!
Play ...
Meow!
Feed ...
Meow!
Sleep ...
Energy: 50
Mood: 53
Hungry: 49

Related Java OOPS Examples


Comments