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);
}
}