this关键字

this可以出现在非static的方法、构造器中。

1、 this关键字出现在非static方法中

  • this代表该方法的调用者(谁调用该方法,this就代表谁)。
public class Pig
{
	String color;
	double weight;
	public void move()
	{
		System.out.println("其实猪跑得很快······");
	} 
	public void test()
	{
		System.out.println("测试方法");
		//主调(主语调用者)
		this.move();
		System.out.println(this.color);
	}
}
public class PigTest
{
	public static void main(String[] args)
	{
		Pig p1 = new Pig();
		p1.color = "白色";
		//p1调用test方法,因此test方法中this代表p1
		p1.test();

		Pig p2 = new Pig();
		p2.color = "黑色";
		//p2调用test方法,因此test方法中this代表p2
		p2.test();
	}
}

2、 this关键字出现在构造器中

  • this的很重要作用是用于区分方法或者构造器的局部变量(尤其是与局部变量同名时)。
  • this代表该构造器正在初始化的对象。
public class Apple
{
	String color;
	double weight;
	public Apple(String color,double weight)
	{
		//构造器正在初始化谁,this代表谁
		this.color = color;
		this.weight = weight;
	}
}
public class AppleTest
{
	public static void main(String[] args)
	{
		//此时构造器正在初始化ap,因此Apple构造其中this代表ap
		Apple ap = new Apple("黄色",0.34);
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值