this 当前对象 实例成员内可以出现
实例属性
实例方法
构造器
用法:1、this 当前对象 2、this() 转发构造器
.
…
.
…//this 当前对象
package jichu3;
//this
public class Student {
String name;
void setName(String name){ //使传进来的参数name等于属性name
this.name=name;
}
public static void main(String[] args) {
//
Student 大星= new Student();
大星.setName("大星");
//大星传给setName的name,然后name给this.name;;
// this.name是当前对象大星的属性name(String name),
// 意思就是用自己的属性name(String name)等于传进来的参数name
Student 海绵= new Student();
海绵.setName("海绵");
Student 居居= new Student();
居居.setName("猪猪");
System.out.println(大星.name);
System.out.println(海绵.name);
System.out.println(居居.name);
}
}
。
。
//this构造器转发
package jichu3;
//this构造器转发
public class Cat {
String name;
int age;
Cat(){
this("猫猫",1);
System.out.println("1");
}
Cat(String name){
this(name,1);
System.out.println("2");
}
Cat(String name,int age){
System.out.println("3");
this.name=name;
this.age=age;
System.out.println(name);
System.out.println("4");
}
public static void main(String[] args) {
new Cat();
new Cat("花花");
}
}