this来表示这个对象本身,在普通方法中,this表示调用这个方法的对象,在构造方法中,this表示新创建的对象。
- 使用this来访问成员变量及调用成员方法
- 使用this 解决成员变量与局部变量同名问题
- 在构造函数中,使用this调用另一个构造方法
此时该调用语句必须放在第一句 - 返回实例对象本身的引用
作为类成员语句return语句的参数,用于返回对象本身的引用 - static修饰的方法或变量不可以使用this来引用
public class Ex5_5_this1 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Cat garfield = new Cat("黄",12);
garfield.grow();
}
}
class Cat{
String furColor;
int height;
public Cat(String furColor) {
this.furColor = furColor; //使用this 解决成员变量与局部变量同名问题 this.furColor代表新创建对象的成员变量furColor ,furColor代表参数变量
this.cry(); //使用this来调用成员方法
}
public Cat(String color,int height) {
this(color); //在构造方法中使用this调用另一个构造函数
this.height= height;
}
public void cry() {
System.out.println("我是一只"+this.furColor+"颜色的猫"); //使用this来访问成员变量
}
public void grow() {
this.height ++;
System.out.println("我长高了,身高为"+this.height);
}
}
程序运行结果:
我是一只黄颜色的猫
我长高了,身高为13
public class Ex5_7_this3 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Dog tom = new Dog();
System.out.println("新生的tom身高:"+tom.height+"cm,年龄:"+tom.age);
tom = tom.grow();
System.out.println("长大的tom身高:"+tom.height+"cm,年龄:"+tom.age);
}
}
class Dog{
int age;
float height;
public Dog() {
age = 1;
height = 10;
}
public Dog grow() { //返回Dog类型数据
height = height +10;
age ++;
return this; //此处的this为当前调用的对象自己
}
}
程序运行结果:
新生的tom身高:10.0cm,年龄:1
长大的tom身高:20.0cm,年龄:2