this 关键字

this:当前类的对象
this 可以在方法内获取到对象中的属性信息
this 还可以区分局部变量和成员变量
public class Car {
	String color;
	int speed;
	int seat = 5;
	
	public void run() {
	//默认会有一个this: 当前正在执行这个方法的对象
	System.out.println(this);
	System.out.println(this.color);
	System.out.println(this.speed);
	//获取到车的颜色和速度
		System.out.println("车能跑");
	}
	
	public void fly() {
		System.out.println(this.color + "颜色的车会飞");
		System.out.println(color + "颜色的车会飞");//  此时访问的也是成员变量
		//变量的查找顺序:先找自己方法内,如果自己没有,就去this里面找
	}
	
	public static void main(String[] args) {
	/*
		Car c = new Car(); // 车中的属性就是类中定义好的成员变量
		c.color = "红色”;
		c.speed = 120;
		
		// 在调用方法的时候,java会自动的把对象传递给方法,在方法中由this来接收对象
		c.run(); 
		//System.out.println(c);
		
		Car c2 = new Car();
		c2.color = "绿色";
		c2.speed = 180;
		c2.run();
	*/
		//this 可以帮我们区分成员变量和局部变量
		Car c = new Car();
		c.color = "绿色";
		
		c.fly("黑色");
	}
}




相关文章:

  • 2021-09-11
  • 2020-02-22
  • 2021-03-31
  • 2021-05-11
  • 2021-04-06
  • 2021-04-02
  • 2021-09-24
  • 2021-07-24
猜你喜欢
  • 2021-07-30
  • 2021-10-13
  • 2021-11-27
  • 2018-09-24
  • 2021-10-14
  • 2022-01-03
  • 2021-07-14
  • 2021-05-03
相关资源
相似解决方案