Is the follwing true: Java getters and setters are just methods.
I know they are implemented to manipulate or get the value of private ... attributes/fields. But is it okay to call them methods?
Is the follwing true: Java getters and setters are just methods.
I know they are implemented to manipulate or get the value of private ... attributes/fields. But is it okay to call them methods?
Yes it's okay they are just methods!
Technically, from the language and VM point of view, yes, they are just methods.
Some libraries and frameworks, however recognize their special nature. For example, JPA may be used to map “properties” by annotating either fields or methods. Beans Binding library uses them to access properties, so if you have a getText() / setText()
pair on some object, then you can bind the “text” property to some other property of some other object (you'll still have to do the addPropertyChangeListener
magic, though). But this is just a “convention over configuration” phenomena combined with the power of Reflection.
As per JLS,
A method declares executable code that can be invoked, passing a fixed number of values as arguments.
And this criterias satisfies to getters and setters as well; so we can say the are "methods" in java language.
Luckily I was able to pull Craig Larman's "Applying UML and Patterns" book section in google. As quoted
Accessing methods retrieve(accessor method) or set(mutator method)
attributes. In some languages such as Java it is a common idiom to
have an accessor and mutator for each attribute, and to declare all
attributes private(to enforce data encapsulation). The methods are
excluded in the class diagram because of the high noise-to-value ratio
they generate."
Java Getters and Setters are accessor methods. So, yes, they are methods.
Many programmers (Java or otherwise) may feel annoyed at constantly writing getXXX()
and setXXX(type t)
for all of their private fields, especially if they are basically just one line methods. For this case, there are some annotation libraries (like Lombak) that generate these through the power of metaprogramming and Java annotations and reflection.
However, there are many reasons to explicitly write getters/setters. A good list can be found here. But I really like this answer, too.
Yes, essentially they are methods. The standard definition for a Java method is as follows;
A method is a set of code which is referred to by name and can be called (invoked) at any point in a program simply by utilizing the method's name.
So you can consider methods as small programs within a class itself that allows us to fulfill specific tasks, which is also exactly what getters and setters do.