First, the definition and role of constructor?
- The method of the class name must be the same name, the constructor does not return type declaration.
- Use the new keyword to instantiate an object when it will automatically call the constructor.
- Java language, at least a default constructor for each class. Once a configuration that defines the display method, the system does not provide a default constructor.
public class People {
private String name;
private int age;
private String sex;
//带参数的构造器
public People(String name, int age, String sex) {
this.name = name;
this.age = age;
this.sex = sex;
}
public static void main(String[] args) {
People people=new People("zhangsan",20,"男");
}
}
The role of the constructor: used to initialize member variables.
When the new People ( "zhangsan", 20, "male"), the People will call method, the object is initialized.
Two, set and get methods Role:
- When we have used variable value constructor to initialize member, you want to modify a variable, the Zenmo to do it?
- If you re new to an object, it is more occupied by memory. Therefore, we can use the get and set methods to complete.
public class People {
private String name;
private int age;
private String sex;
//带参数的构造器
public People(String name, int age, String sex) {
this.name = name;
this.age = age;
this.sex = sex;
}
//get方法获取字段
public int getAge() {
return age;
}
//set方法修改字段
public void setAge(int age) {
this.age = age;
}
public static void main(String[] args) {
People people=new People("zhangsan",20,"男");
people.setAge(22);
System.out.println(people.getAge());
System.out.println(people.name);
System.out.println(people.sex);
}
}
- For members of the private modified, if you want to use outside the class, so what?
- At this point, if needs to obtain or modify private property, you need to use getter / setter methods.
public class Test {
public static void main(String[] args) {
People people=new People("zhangsan",20,"男");
people.setAge(22);
System.out.println(people.getAge());
}
}
methods set and get the role: to modify properties and acquisition; easy to modify, enhance the maintainability of the code; good encapsulation.
Third, the difference between the set and the constructor methods, GET method:
Constructor: used to initialize the object.
set, get method: for member variables to modify, re-assignment; on private property is acquired.