Java之this关键字

this是Java的一个关键字,表示某个对象。this可以出现在实例方法和构造方法中,但不可以出现在类方法中

 

 一:在构造方法中使用this

this关键字出现在类的构造方法中时,代表使用该构造方法所创建的对象

public class This_keyword {
	int hand,mouse;
	String name;
	This_keyword(String s){
		name = s;
		this.init();
	}
	void init(){
		mouse = 1;
		hand = 2;
		System.out.println(name + "有" + hand + "只手");
	}

	public static void main(String[] args) {
		This_keyword people = new This_keyword("Andy");
		//创建people时,构造方法中的this就是指对象people
	}
}

其中在构造方法people(String s)中,this是可以省略的,即"this.init()"可以改成"init()"。 

二:在实例方法中使用this

实例方法只能通过对象来调用(即你创建了一个对象,调用一个实例方法 对象名.实例方法名() ),不能用类名来调用(也就是不能 类名.方法名 这样使用)。当this关键字出现在实例方法中时,this就代表正在调用该方法的当前对象。例如:

public class This_keyword {
	static int hand;
	String name;
	void init(String s){
		this.name = s;
		This_keyword.hand= 2;
		System.out.println(name + "有" + hand + "只手");
	}

	public static void main(String[] args) {
		This_keyword people = new This_keyword();
		people.init("Andy");
	}
}

通常情况下,是可以省略实例成员变量名字前面的“this.”以及static变量前面的“类名.”的。

But,当实例成员变量的名字与局部变量的名字相同时,成员变量名字前面的“this.”或“类名.”就不可以省略。例如:

public class This_keyword {
	static int hand;
	String name;
	void init(String s){
		this.name = s;
		this.hand= 2;
		int hand = 8;
		System.out.println(name + "有" + this.hand + "只手");
		System.out.println(name + "有" + hand + "只手");
		//加this.与不加this.的结果是不一样的!
	}

	public static void main(String[] args) {
		This_keyword people = new This_keyword();
		people.init("Andy");
	}
}

 

猜你喜欢

转载自blog.csdn.net/weixin_42227243/article/details/82820442