Java中的this关键字

时间:2023-03-09 15:53:53
Java中的this关键字
//Java中的this

//this引用---->当前对象的引用
/*
 * 1.this在什么地方(非静态的)访问另外一个成员(非静态,可以是属性或者方法)
 * 前面都省略了this
 * 2.什么是this:当前对象(的引用) 调用这个函数的那个对象(的引用)
 * 案例:初始化的时候形式参数的变量名可以和成员一样,成员前用this区分
 */

class Point{

	double x , y ;
	//构造方法可以重载,设置不同的参数即可
	Point(int a , int b){
		//x = a ;  //访问了另一个成员,省略了this
		this.x = a ;//实际上是这样写
		y = b ;
	}
	//此时为了更好的区分,所以就用this来区分,参数名可以和成员名一样。
	Point(double x , double y){
		//这种情况下this不能省略
		this.x = x ;
		this.y = y ;
	}
	void showLocation() {
		//省略了this
		System.out.println("x"+x+"y:"+y);
	}
	Point getx(){
		x++;
		return this ;
	}

}
public class HelloWorld {
	public static void main(String[] args){
		//p1就是一个对象
		Point p1 = new Point(10,100);
		p1.showLocation();

	}
}