OBJECT-ORIENTED PROGRAMMING
Java getters and setters
Getters and setters are methods that control reading and changing private object fields. They are a common way to apply encapsulation in Java programs.
Why hide fields?
Encapsulation protects an object's internal state from uncontrolled external changes. Usually:
- class attributes are declared with
private; - the value is read through a public getter;
- the value is changed through a public setter, if changes are allowed;
- the setter can validate the value before saving it.
Creating a getter and setter
public class Knyga {
private String pavadinimas;
public String getPavadinimas() {
return pavadinimas;
}
public void setPavadinimas(String naujasPavadinimas) {
this.pavadinimas = naujasPavadinimas;
}
}Only the class and its methods are defined here. No object is created and no methods are called, so nothing is printed.
- The attribute
pavadinimasisprivate, so external code cannot access it directly. getPavadinimas()is a getter: it returns the attribute's current value.setPavadinimas(...)is a setter: it accepts new text.this.pavadinimasmeans the object's attribute, whilenaujasPavadinimasis the setter's parameter.- The class decides which public methods may read or change its data.
| The method | Purpose | Result |
|---|---|---|
getPavadinimas() | Read a field | Returns String |
setPavadinimas(...) | Change a field | Accepts a parameter and usually returns void |
this.pavadinimas refers to the object's field, while naujasPavadinimas is the setter's parameter.
Direct access is not allowed
Code outside the class cannot directly access a private field:
Knyga knyga = new Knyga();
knyga.pavadinimas = "Mažasis princas";
System.out.println(knyga.pavadinimas);error: pavadinimas has private access in Knyga
- The code tries to write a value directly to
knyga.pavadinimas. - However, the attribute
pavadinimasis markedprivate. - therefore cannot be changed or read outside the
Knygaclass. - The compiler rejects the program, so there is no normal console output.
Use the public methods provided by the class instead:
public class Main {
public static void main(String[] args) {
Knyga knyga = new Knyga();
knyga.setPavadinimas("Mažasis princas");
System.out.println(knyga.getPavadinimas());
}
}Mažasis princas
- The setter
setPavadinimas()receives the text Mažasis princas. - Since the setter is a method of the class itself, it can change the private attribute.
- The getter
getPavadinimas()reads and returns the stored value. println()displays the title returned by the getter.
Validating data in a setter
A setter protects the object's state from invalid values. A book's page count must be greater than zero:
public class Knyga {
private int puslapiuSkaicius;
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(96);
System.out.println(knyga.getPuslapiuSkaicius());
knyga.setPuslapiuSkaicius(-5);
System.out.println(knyga.getPuslapiuSkaicius());
}
}96
Puslapių skaičius turi būti teigiamas
96
- The first setter call passes the valid value
96. - Condition
96 <= 0is false, so the attribute is updated successfully. - The second call passes the invalid value
-5. - The setter displays an error message and uses
returnto exit before changing the attribute. - The final getter call therefore still returns the previous valid value,
96.
Any external code could assign, for example, -5 pages and leave the object in an invalid state.
A read-only field
Not every field needs a setter. If only a getter is provided, external code can read the value but cannot change it:
public class Knyga {
private final String isbn;
public Knyga(String isbn) {
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 attribute is both
privateandfinal. - Its value is assigned in the constructor when the object is created.
- The getter
getIsbn()lets external code read the value. - There is no setter, so the class provides no way to change the ISBN.
finaladditionally ensures that the attribute cannot receive a different value after assignment.
Naming a boolean getter
By common Java naming convention, getters for Boolean properties often start with is:
public class Knyga {
private boolean perskaityta;
public boolean isPerskaityta() {
return perskaityta;
}
public void setPerskaityta(boolean perskaityta) {
this.perskaityta = perskaityta;
}
public static void main(String[] args) {
Knyga knyga = new Knyga();
knyga.setPerskaityta(true);
System.out.println(knyga.isPerskaityta());
}
}true
- The private attribute
perskaitytainitially has the default valuefalse. - The setter
setPerskaityta(true)changes it totrue. - The Boolean attribute's getter is named
isPerskaityta(). - The getter returns the current value, and
println()displays it in the console.
Naming conventions
- For the field
pavadinimasusegetPavadinimas()andsetPavadinimas(...). - Capitalize the first letter of the field name within the method name.
booleangetter is often namedisPerskaityta().- A setter's parameter type must match the field type.
Not every field needs get and set
Automatically generating getters and setters for every field can weaken encapsulation. Expose only the operations actually needed. Sometimes a clearer method is perskaitytiPuslapius(10)rather than a direct setPerskaitytaPuslapiu(10), because it better describes the object's behavior.