Understanding Getter and Setter in Java


Getter and Setter is new things for me since I have experience in Python which all attribute in a Class can be invoked anytime. It’s different in Java which all data should be thread-safe and manipulation between data should be isolated and not interfere another process/task.

Btw, did i mean “encapsulation” here? Well, there are a lot of long debate about Getter/Setter whether is part of encapsulation or not. But from my own perspective, Getter/Setter is more likely integration and interfacing.

Imagine, we have a Class that provide calculation of Student behaviour. We have sub-routine/function inside this class for processing student name. This function called “firstname”. There is another class which want to use this firstname() to get the student name. Then, Getter/Setter is the player here. Getter/Setter will invoke method firstname() to be able use by another class.

Example code TestPerson.java:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Person {
    private String firstname = null;

    public void setFirstname(String firstname){
         /* Imagine there a lot of calculation things here */
        this.firstname = firstname;
    }

    public String getFirstname() {
        return firstname;
    }
}

public class TestPerson {
    public static void main(String args[]) {
        Person p = new Person();
        p.setFirstname("Yodiaditya");
        System.out.println(p.getFirstname());
    }
}


You can running this code by:

1
javac TestPerson.java && java TestPerson

So, this is how Getter/Setter works in Java. You can put whatever data processing data inside a Class and make them accessible (interface) to another class which want to use.


Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.