Java面向对象--this关键字

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("黑色");
	}
}




猜你喜欢

转载自www.cnblogs.com/isChenJY/p/12726990.html