I've been reading some Java books lately, but there is a part that makes me confused about this type of accessor method – gettters and setters.
The question is:
Do I have to write these types of methods, for example, getName() or do I just have to write getName() because it makes life easier for the programmer to better serve object-oriented programming? Is the way of making getters or setters a norm or a convention?
If I write, for example, byName() instead of getName() the compiler doesn't declare a syntax error and fulfills the same function, just change the method name.
Is the way of making getters or setters a norm or a convention?
It is a convention determined by the company that maintains the language, Oracle, as you can see in: JavaBeans Standard
The JavaBeans spec document determines in addition to these numerous other conventions, all of them with the aim of facilitating communication between developers . JavaBeans are Java classes that have properties. Properties are instance variables with the private modifier.
Some of the conventions that refer to class properties are:
- If the property is not a boolean , the accessor method that takes the property must start with get . Example:
- If the property is a boolean , the accessor method that takes the property can start with either get or is . Example:
- The accessor method that assigns a value to the property must start with set . Example:
- The accessor methods (getters and setters) must be written in the camelCase pattern;
- To compose the name of an accessor method the first word must be either get , set , or is , and the rest of the method name must be exactly the same as the attribute name;
- Setter methods must be public with a void return;
- Getter methods must be public, have no parameters, and have a return type that matches that of the property.