Encapsulation Example, Cameron Sapp - norvell/preAPCS-4th-1415 GitHub Wiki

Encapsulation is a fundamental concept of Object Oriented Programming in which all elements of a class are entirely self-contained. It is used to chunk sections of code, so that it is possible to easily modify objects of a class without editing that class itself. It also prevents a class's variables from being accessed randomly by other classes.

Example:

public class Player {
    private String name;
    private int health;
    private int attack;

    public String getName() {
        return name;
    }
    public int getHealth() {
        return health;
    }
    public int getAttack() {
        return attack;
    }
    public void setName(String newname) {
        name = newname;
    }
    public void setHealth(int newhealth) {
        health = newhealth;
    }
    public void setAttack(int newattack) {
        attack = newattack;
    }
}

public class Main {
    public static void main(String[] args) {
        Player play = new Player();
        play.setName("Cameron");
        play.setHealth(100);
        play.setAttack(20);
        System.out.println("Player name: " + play.getName()
            + "\nHealth: " + play.getHealth()
            + "\nAttack: " + play.getAttack());
    }
}