views:

555

answers:

3

What are getter methods and setter methods in Java? What is their technical term in Java?

+1  A: 

Getter and Setter methods are ways to access internal variables of a class externally.

They are much safer than setting the variable to be public as you can guarentee usage and thread-safety.

I found this thread through a google search:.

Alastair Pitts
Um no, they are pretty much exactly the same as setting the variable to public. They are a horrible antipattern and I wish borland had never hacked them into the java mindset as a stupid way to get their design tools to work.
Bill K
They are definitely not 'antipatterns', ignoring the wrong use of the term here. Imagine the situation where you need to debug your code, do you want to find all places where the variable is changed or just put a println/breakpoint in the setter? I know what I'd rather do... And then there are all the interface arguments.
NomeN
Getters and setters allow validation logic. Changing a public field to getter and setters is a breaking change, so people usually use getters and setters in stead of public fields in case they need to add validation logic later.
Joren
+2  A: 

Getter and setter methods are methods that are used to manipulate the value of a single "property" of an object.

Usually, the names of these methods are getProperty() and setProperty(PropertyType value), where Property is the name of the property which these methods modify/access.

Example

class Person {
    private String name; // the property "name"
    public String getName(); // getter for the property "name"
    public void setName(String newName); // setter for the property "name"
}

And, "setter" and "getter" are/have now become universally consistent terms in the programming world. As far as I know, they are the technical terms. If they are not, you can still use them without fear of being misunderstood.

Cheers,
jrh

Here Be Wolves
The technical term is 'accessor methods', with the problem that people may not know what you're talking about ;-).
NomeN
A: 

A frequently used term for these methods is 'accessor methods', and probably the best rule of thumb is to only use them if they are needed, and if you do use them use only the narrowest visibility required.

Leigh
I have also heard the phrase "mutators" used to describe setters.
Adamski
I'd +1 the "accessor methods" and -1 the "only use them if you need them". So nothing from me, sorry.
NomeN