Java中的this

this来表示这个对象本身,在普通方法中,this表示调用这个方法的对象,在构造方法中,this表示新创建的对象。

  1. 使用this来访问成员变量及调用成员方法
  2. 使用this 解决成员变量与局部变量同名问题
  3. 在构造函数中,使用this调用另一个构造方法
    此时该调用语句必须放在第一句
  4. 返回实例对象本身的引用
    作为类成员语句return语句的参数,用于返回对象本身的引用
  5. 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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值