The method that sets (sets) a value in a Java object field is ** setter **. The value to get the value is ** getter **.
By convention, the names, arguments, and return values are as follows.
Method name | argument | Return value | |
---|---|---|---|
Getter | getXXX() | No arguments | Field value |
Setter | setXXX() | One argument | void type |
To make the contents of the objects that form a program as invisible as possible from other objects. The principle of encapsulation is to make all fields private so that other classes cannot access them.
private type name field name();
Fields made private by encapsulation cannot be accessed directly by other classes. Provide a means of indirect access in case you need to access it. Specifically, prepare the following methods for indirect access.
Return type method name(){
return field name;
}
This method is just a method that returns the value of the field with return. Therefore, the return type is the same as the field type. For example
private int piyo;
Against
public int getPiyo(){
return piyo;
}
Will be.
Made it private by calling the "getPiyo ()" method in another class You will be able to get the value of the int type field "piyo". In short, by calling the getter from another class, you get the value of the private field as the return value. This is a getter. This way, even if there is a change in the field name or value acquisition logic, the "getPiyo ()" method All you have to do is rewrite the inside. It also has the advantage that you don't have to rewrite other classes that use the "getPiyo ()" method.
The getter found that we could get the value of a private field. However, since the getter is a method that just returns the value of the field with return, the value of the field cannot be rewritten. The method for rewriting the value is the setter. Generally, prepare the following methods.
Return type method name(argument){
Field name=argument;
}
This method takes the value you want to enter in the field as an argument and just assigns it to the field in the method, so the argument type is the same as the field. For example
private int hoge;
Against
public void setPiyo(int piyo){
piyo = hoge;
}
Will be. This just assigns the value "hoge" received as an argument to the field "piyo". Like getters, this way, even if something changes, the "setPiyo ()" method in the class All you have to do is rewrite the inside. There is also the advantage that you do not have to rewrite other classes that use the "serPiyo ()" method.
A method prepared for indirectly accessing a field hidden by pravate, such as a setter or getter, is called a ** accessor method **. By accessing the field using the accessor method, it is possible to reduce the dependency between classes, make the work of addition / modification easier, and increase the degree of freedom.
Recommended Posts