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;
    }
}
There is no console output.

Only the class and its methods are defined here. No object is created and no methods are called, so nothing is printed.

  1. The attribute pavadinimas is private, so external code cannot access it directly.
  2. getPavadinimas() is a getter: it returns the attribute's current value.
  3. setPavadinimas(...) is a setter: it accepts new text.
  4. this.pavadinimas means the object's attribute, while naujasPavadinimas is the setter's parameter.
  5. The class decides which public methods may read or change its data.
The purpose of a getter and setter
The methodPurposeResult
getPavadinimas()Read a fieldReturns String
setPavadinimas(...)Change a fieldAccepts 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);
Compiler result

error: pavadinimas has private access in Knyga

  1. The code tries to write a value directly to knyga.pavadinimas.
  2. However, the attribute pavadinimas is marked private.
  3. therefore cannot be changed or read outside the Knyga class.
  4. 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());
    }
}
Console output

Mažasis princas

  1. The setter setPavadinimas() receives the text Mažasis princas.
  2. Since the setter is a method of the class itself, it can change the private attribute.
  3. The getter getPavadinimas() reads and returns the stored value.
  4. 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());
    }
}
Console output

96
Puslapių skaičius turi būti teigiamas
96

  1. The first setter call passes the valid value 96.
  2. Condition 96 <= 0 is false, so the attribute is updated successfully.
  3. The second call passes the invalid value -5.
  4. The setter displays an error message and uses return to exit before changing the attribute.
  5. The final getter call therefore still returns the previous valid value, 96.
A public field would not provide this control.

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());
    }
}
Console output

978-609-01-0000-0

  1. The ISBN attribute is both privateand final.
  2. Its value is assigned in the constructor when the object is created.
  3. The getter getIsbn() lets external code read the value.
  4. There is no setter, so the class provides no way to change the ISBN.
  5. final additionally 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());
    }
}
Console output

true

  1. The private attribute perskaityta initially has the default value false.
  2. The setter setPerskaityta(true) changes it to true.
  3. The Boolean attribute's getter is named isPerskaityta().
  4. The getter returns the current value, and println() displays it in the console.

Naming conventions

  • For the field pavadinimas use getPavadinimas() and setPavadinimas(...).
  • Capitalize the first letter of the field name within the method name.
  • boolean getter is often named isPerskaityta().
  • 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.