OBJECT-ORIENTED PROGRAMMING

Java encapsulation

Encapsulation hides an object's internal state and exposes it only through a clearly defined public interface. The object controls which changes to its data are allowed.

Why is encapsulation needed?

  • protects objects from invalid states;
  • hides internal implementation details;
  • provides one place to validate data;
  • lets you change the implementation without changing client code;
  • clearly shows which operations the class allows.

The problem with a public field

Any code can change a public attribute without the class controlling it:

public class Knyga {
    public int puslapiuSkaicius = 96;

    public static void main(String[] args) {
        Knyga knyga = new Knyga();
        knyga.puslapiuSkaicius = -5;

        System.out.println(knyga.puslapiuSkaicius);
    }
}
Console output

-5

  1. The attribute puslapiuSkaicius is public, so any external code can change it.
  2. The initial valid value is 96.
  3. External code directly writes -5, even though a book cannot have a negative page count.
  4. The class has no opportunity to validate or reject this change.
  5. The object remains in an illogical state, and the console shows -5.

Private state and controlled access

The field is hidden using private, and public methods define the rules for reading and changing it:

public class Knyga {
    private int puslapiuSkaicius = 96;

    public int getPuslapiuSkaicius() {
        return puslapiuSkaicius;
    }

    public void setPuslapiuSkaicius(int naujasSkaicius) {
        if (naujasSkaicius <= 0) {
            System.out.println("Puslapių skaičius turi būti teigiamas");
            return;
        }

        this.puslapiuSkaicius = naujasSkaicius;
    }

    public static void main(String[] args) {
        Knyga knyga = new Knyga();
        knyga.setPuslapiuSkaicius(-5);

        System.out.println(knyga.getPuslapiuSkaicius());
    }
}
Console output

Puslapių skaičius turi būti teigiamas
96

  1. The attribute is now private, so external code cannot change it directly.
  2. The value can be changed only through the setter setPuslapiuSkaicius().
  3. The setter first checks whether the supplied number is greater than zero.
  4. Meaning -5 is invalid, so a message is displayed and the method exits with return.
  5. The object's state stays unchanged, so the getter still returns the valid value 96.

Encapsulation is more than getters and setters

Sometimes it is better to expose a meaningful object action than a generic setter. It is safer to reduce a book's remaining page count through a method that validates the reading action:

public class Knyga {
    private int likoPuslapiu = 96;

    public int getLikoPuslapiu() {
        return likoPuslapiu;
    }

    public boolean skaityti(int puslapiai) {
        if (puslapiai <= 0 || puslapiai > likoPuslapiu) {
            return false;
        }

        likoPuslapiu -= puslapiai;
        return true;
    }

    public static void main(String[] args) {
        Knyga knyga = new Knyga();

        System.out.println(knyga.skaityti(20));
        System.out.println(knyga.getLikoPuslapiu());
        System.out.println(knyga.skaityti(100));
        System.out.println(knyga.getLikoPuslapiu());
    }
}
Console output

true
76
false
76

  1. The book initially has 96 pages.
  2. skaityti(20) is valid, so the method subtracts 20, leaving 76 and returns true.
  3. The next attempt is to read 100 pages, although only 76 remain.
  4. The method rejects the action, returns false and leaves the attribute unchanged.
  5. After both attempts, the remaining page count is therefore still 76.
skaityti() expresses a meaningful object action.

A generic setter would let external code set any remaining page count and bypass the reading rules.

Immutable and read-only state

If a value must not change after object creation, use a private final field and provide only a getter:

public class Knyga {
    private final String isbn;

    public Knyga(String isbn) {
        if (isbn == null || isbn.isBlank()) {
            throw new IllegalArgumentException("ISBN privalomas");
        }

        this.isbn = isbn;
    }

    public String getIsbn() {
        return isbn;
    }

    public static void main(String[] args) {
        Knyga knyga = new Knyga("978-609-01-0000-0");
        System.out.println(knyga.getIsbn());
    }
}
Console output

978-609-01-0000-0

  1. The ISBN is passed to the constructor when creating the book object.
  2. The constructor rejects an empty or null value.
  3. The validated value is stored in the private, final final attribute.
  4. A public getter lets you read the ISBN.
  5. There is no setter, so external code cannot ask the class to change the ISBN.

Be careful with mutable objects

Using private alone is insufficient if a getter returns a reference to a mutable object. For a collection, you can return an unmodifiable copy:

import java.util.ArrayList;
import java.util.List;

public class Knyga {
    private final List pastabos = new ArrayList<>();

    public void pridetiPastaba(String pastaba) {
        pastabos.add(pastaba);
    }

    public List getPastabos() {
        return List.copyOf(pastabos);
    }

    public static void main(String[] args) {
        Knyga knyga = new Knyga();
        knyga.pridetiPastaba("Perskaityti dar kartą");

        List kopija = knyga.getPastabos();
        System.out.println(kopija);
    }
}
Console output

[Perskaityti dar kartą]

  1. The internal notes list is private, so it is managed by the Knyga class itself.
  2. A note is added through the public method pridetiPastaba().
  3. The getter does not return a direct reference to the internal list.
  4. List.copyOf(pastabos) creates an unmodifiable copy of the list.
  5. External code can read the notes but cannot use this copy to secretly change the internal list.

Public interface and internal implementation

Parts of an encapsulated class
PartExamplesPurpose
Public interfacepublic methodsOperations available to class users
Internal implementationprivate fields and helper methodsData and details managed by the class itself

Practical guidelines

  • Keep fields private by default: private.
  • Expose behavior rather than every possible change to internal state.
  • Validate object rules in constructors and methods that change state.
  • Do not create a setter just because a field exists.
  • Do not return direct references to internal mutable collections.