[Java] Java encapsulation and getters and setters

1 minute read

Encapsulation

When developing with some people, when you create a class, expose the features you want to use and hide the features you don’t want to use outside the class so that others can use the class.
Specifically, it restricts access to fields and methods.
Use “public” to make it accessible from outside the class, and “private” to make it inaccessible.
[Example]

public String name;  //Can be accessed from outside the class
private String name;  //Not accessible from outside the class

Getter

In “private” earlier, I made it impossible to access the field from outside the class.
However, even “private” can be accessed from within the class.
What you do is make the field “private” and define a method that just returns the value of the field in order to get the value of the field from outside the class. This is called a ** getter **.
It seems that getters are generally named like “get field name”.
[Example] The class is Person

class Person {
public Return type get field name() {
    //Returns the value of the field
  }
}

Setter

If you set the field permissions to “private”, you cannot change the value of the field from outside the class.
Therefore, define a method to change the value of the field.
The method of changing the value of a field is especially called a “setter”.
It seems that setters are generally named like “set field name”.
I think it’s okay to remember that the standard encapsulation is “private” for fields and “public” for methods.
[Example]

class Person {
public void set field name(Data type dummy argument) {
    //Set value in field
  }
}

Tags:

Updated: