Getters and setters in java | Core Java Forum
P
Petchimuthu Pandiyan Posted on 05/01/2021

Hi ,

can anyone confirm what is the purpose of using getters and setters in java. And what are all the instances we can use it.


Y
Yogesh Chawla Replied on 05/01/2021

See this:

private String myField; //"private" means access to this is restricted

public String getMyField()
{
//include validation, logic, logging or whatever you like here
return this.myField;
}
public void setMyField(String value)
{
//include more logic
this.myField = value;
}

so getter is a method to get a private field and setter is a method to set a new field.

The reason for using getters and setters instead of making your members public is that it makes it possible to change the implementation without changing the interface. Also, many tools and toolkits that use reflection to examine objects only accept objects that have getters and setters. JavaBeans for example must have getters and setters as well as some other requirements.

 

See this example:

class Clock {
String time;

void setTime (String t) {
time = t;
}

String getTime() {
return time;
}
}


class ClockTestDrive {
public static void main (String [] args) {
Clock c = new Clock;

c.setTime("12345")
String tod = c.getTime();
System.out.println(time: " + tod);
}
}

When you run the program, program starts in mains,

object c is created
function setTime() is called by the object c
the variable time is set to the value passed by function getTime() which is called by object c and the time is returned
In the end, we are printing the time as output.