Understanding of set(), get() methods
Why use set() and get() method
When we instantiate a class object, we must assign the properties of this class object and output the properties of this class.
To give an example:
If a Person class is defined, the name and age of the Person class should be assigned.
public class Demo {
public static void main(String[] args) {
Person person = new Person();
= "Zhang San";
= 18;
("Name:"++",Age:"+);
}
}
class Person{
String name;
int age;
}
If so, the result should be:
Name: Zhang San, Age: 18
Why use get() and set() methods
Generally speaking, attributes are the privacy of the class and not everyone can access it.
This is the enclosure and security in object-oriented programming of JAVA.
Then we need to add private to the name and age of the Person class to modify it, but after adding private, the external class cannot be accessed, so an error will be reported by and. At this time, we need to use the set() and get() methods.
Use of set() and get()
set is the incoming value
get is to get the value
Regardless of your attribute (Xxx) is just:
public void setXxx(String Xxx) {
= Xxx;
}
public String getXxx() {
return Xxx;
}
Therefore, no matter what attributes are, they can be inputted through the set() method and the get() method.
example:
public class Demo {
public static void main(String[] args) {
Person person = new Person();
("teacher");
(18);
("Zhang San");
("Name:" + () + ", age:" + () + "Occupation:" + ());
}
}
class Person {
private String occupation;
private String name;
private int age;
public void setOccupation(String occupation) {
= occupation;
}
public String getOccupation() {
return occupation;
}
public void setName(String name) {
= name;
}
public String getName() {
return name;
}
public void setAge(int age) {
= age;
}
public int getAge() {
return age;
}
}
result:
Name: Zhang San, Age: 18 Occupation: teacher
Maybe you will ask that and setAge() both obtain age values from the outside world, and everything is the same?
What if the age you entered is negative? Does it also mean it is age?
Use the set() method to determine whether the input value is correct in the method.
Summary: In order to make the program safer, in addition to using the set() and get() methods, we can actually use constructors.