By not exposing the field, we apologize for the field value that should not be changed so that it cannot be changed.
name | How to write in the program | Scope of permission for access |
---|---|---|
private | private | Only in the same class as myself |
package private | Write nothing (default) | Only the same package as myself |
protected | protected | Child classes that belong to the same package as themselves or inherit from themselves |
public | public | All classes |
** (Thinking) **
Basically, private
is often used for fields. Each time a method is created, the scope of application is considered.
getter
** (How to use) **
public A type that returns a value get field name(){
return this.Field name;//
}
(code)
private String name;
public String getName(){
return this.name;//Returns the value of name for this class
}
** (Calling method) **
System.out.println(getName());
setter
** (How to use) **
public void set field name (data type of argument variable name to put argument){
this.Field name = variable name to put the argument
}
(code)
private String name;
public void setName(String name){
this.name = name
}
** (Calling method) **
Instance name.setName("Yoshihiko");
** Read Only Write Only field can be realized. ** ** → write Only for set only, Read Only for get only
** Easy to change field names ** → When renaming a field, if another class uses the field name directly, it will be necessary to modify the other class, but if get / set is used, it will be in your own class. All you have to do is modify the class name in get / set.
** You can check access to the field **
→ (Example) If a value of 0 or less is assigned to the field called mp, an error will be forcibly generated with throw new IllegalArgumentException
and the system will be terminated.
public void setMp(int mp) {
if (mp < 0) {
throw new IllegalArgumentException("Set mp to 0 or more");
}
mp = this.mp;
}
name | How to write in the program | Scope of permission for access |
---|---|---|
public | public | all |
package private | Write nothing (default) | Only the same package as myself |
-The class name may be different from the source file name -Multiple classes may be declared in one source file