- 使用this调用成员变量和成员函数
classPerson{
String name;
void talk(){
System.out.println("my name is "+this.name);
}
}
classTestA{
publicstaticvoid main(String args[]){
Person p1 =newPerson();
p1.name ="zhangsan";
Person p2 =newPerson();
p2.name ="lisi";
p1.talk();
p2.talk();
}
}
- 使用this调用构造函数
- 对this的调用函数必须是构造函数的第一个语句
classTestA{
publicstaticvoid main(String args[]){
Person p1 =newPerson("zhangsan",20,"beijing");
}
}
classPerson{
String name;
int age;
String address;
Person(){
System.out.println("无参数的构造函数");
}
Person(String name,int age){
this();
this.name = name;
this.age = age;
System.out.println("两个参数的构造函数");
}
Person(String name,int age,String address){
this(name,age);
this.address = address;
System.out.println("三个参数的构造函数");
}
}
时间: 2024-11-05 18:39:47