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);
}
}-5
- The attribute
puslapiuSkaiciusispublic, so any external code can change it. - The initial valid value is
96. - External code directly writes
-5, even though a book cannot have a negative page count. - The class has no opportunity to validate or reject this change.
- 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());
}
}Puslapių skaičius turi būti teigiamas
96
- The attribute is now
private, so external code cannot change it directly. - The value can be changed only through the setter
setPuslapiuSkaicius(). - The setter first checks whether the supplied number is greater than zero.
- Meaning
-5is invalid, so a message is displayed and the method exits withreturn. - 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());
}
}true
76
false
76
- The book initially has
96pages. skaityti(20)is valid, so the method subtracts 20, leaving76and returnstrue.- The next attempt is to read
100pages, although only 76 remain. - The method rejects the action, returns
falseand leaves the attribute unchanged. - 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());
}
}978-609-01-0000-0
- The ISBN is passed to the constructor when creating the book object.
- The constructor rejects an empty or
nullvalue. - The validated value is stored in the private, final
finalattribute. - A public getter lets you read the ISBN.
- 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);
}
}[Perskaityti dar kartą]
- The internal notes list is
private, so it is managed by theKnygaclass itself. - A note is added through the public method
pridetiPastaba(). - The getter does not return a direct reference to the internal list.
List.copyOf(pastabos)creates an unmodifiable copy of the list.- External code can read the notes but cannot use this copy to secretly change the internal list.
Public interface and internal implementation
| Part | Examples | Purpose |
|---|---|---|
| Public interface | public methods | Operations available to class users |
| Internal implementation | private fields and helper methods | Data 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.