Java-This keyword: When the local variable and the member variable have the same name, the method of using the member variable in the member method

package Myfirst_package;
//this 关键字:当局部变量和成员变量重名时,成员变量就会被隐藏,这是如果想在成员方法中使用成员变量,必须使用this 关键字
public class Fruit {
    
    
	public String color = "绿色";
	public void harveat() {
    
    
		String color = "红色";
		System.out.println("水果是"+color+"的");
		System.out.println("水果已经收获");
		System.out.println("水果是"+this.color+"的");   //使用成员变量,使用this关键字
	}
	public static void main(String[] args) {
    
    
		Fruit obj = new Fruit();  //创建Fruit的对象obj
		obj.harveat();
	}
}
结果:
水果是红色的
水果已经收获
水果是绿色的

Guess you like

Origin blog.csdn.net/qq_43516928/article/details/114788421