Think of a class as a concept of things in the real world, and think of instantiation as the materialization of that image. And I think that encapsulation is a means to confirm the existence of an entity. Specifically, the code is as follows.
//Class of concept of human
public class Human {
//Humans have three attributes: age, gender, and power.
private int age = 0;
private String gender = new String();
private double power = 0.0;
//The above three attributes must be set for the materialization of human beings.
//It ’s not humans who do n’t have these attributes.
public Human(int age, String gender, double power) {
this.age = age;
this.gender = gender;
this.power = power;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public double getPower() {
return power;
}
public void setPower(double power) {
this.power = power;
}
}
If you instantiate this class, one person will be born.
The existence of setter makes it possible to change a part of the born person.
The question arises here.
The existence of human beings should change the value of the attribute in relation to some event. But why is it possible to change one attribute value? It feels like a procedural language.
For example, when ʻagechanges, it may also affect
power. In that case, you should prepare a method like ʻupAge ()
.
Also, let's assume that you have added the Cloth
of the Cloth object
to the attribute, assuming that you are dressed as a human being. Then, when you put on your clothes, you pass the Cloth object
as a setter. However, this is not considered object-oriented. Clothes should only be ancillary to Human
. The clothes themselves are not elements of the object. In this case, you should inherit the class and create a ModernHuman class
.
In many cases, the setter is a mismatched writing style for object orientation.
At least, I think it's better not to enter the superclass.
However, the setter also has a meaning. It is a required writing method in JavaBeans. Thanks to that, it is possible to write with high readability when calling the element of request with the EL expression etc. in the jsp file. In addition, it is a recommended writing method even for APIs that I do not know.
We have also heard that it was needed in the process of migrating from C language.
This is my opinion for half a year after studying Java. I don't think this is always correct, but I personally feel that it makes sense. I would be grateful if anyone could correct me. that's all.
Recommended Posts