重学java-9.初步认识this关键字

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/euzmin/article/details/89280118

初步认识this关键字

调用本类属性

举个例子:

class Emp {
	private int id;
	private String name;
	private double sal;
	private String dept;
//最常用的就是用this代表本类属性,比如this.id=id就方法中的参数id给类中的参数id赋值
	public Emp(int id, String name, double sal, String dept) {
		this.id = id;
		this.name = name;
		this.sal = sal;
		this.dept = dept;
	}
}

调用本类普通方法

举个例子:

class Emp {
	private int id;
	private String name;
	private double sal;
	private String dept;

	public Emp(int id, String name, double sal, String dept) {
		this.id = id;
		this.name = name;
		this.sal = sal;
		this.dept = dept;
		this.getInfo();//调用本类方法
	}
	public String getInfo() {
		return "id: "+ id +" name: "+ name + " sal: " + sal + " dept: " + dept;
	}
}

调用构造方法

举个例子,把有4个参数的所有构造方法写出来。

class Emp {
	private int id;
	private String name;
	private double sal;
	private String dept;
	public Emp() {
		this(0,"nobody",0.0,"none");
	};
	public Emp(int id) {
		this(id,"nobody",0.0,"none");
	}
	public Emp(int id, String name) {
		this(id,name,0.0,"none");
	}
	public Emp(int id, String name, double sal) {
		this(id,name,sal,"none");
	}
	//前三个构造方法都调用第四个构造方法,节省了许多的重复代码
	public Emp(int id, String name, double sal, String dept) {
		this.id = id;
		this.name = name;
		this.sal = sal;
		this.dept = dept;
		this.getInfo();
	}
	public String getInfo() {
		return "id: "+ id +" name: "+ name + " sal: " + sal + " dept: " + dept;
	}
}

注意: 用this调用本类方法的时候,一定要注意保留出口,否则会无限递归。

表示当前对象

举个例子:

class Emp {
	private int id;
	private String name;
	private double sal;
	private String dept;
	
	public Emp getInfo() {
		return this;//返回的是对象
	}
}

测试代码:

public static void main(String[] args) {
		Emp empa = new Emp();
		Emp empb = new Emp();
		System.out.println(empa + " " + empa.getInfo());
		System.out.println(empb + " " + empb.getInfo());
	}

输出结果:
在这里插入图片描述
可以看出,this所指的内存与调用该方法的对象实体保持一致。

猜你喜欢

转载自blog.csdn.net/euzmin/article/details/89280118