Re learn java-9. Preliminary understanding of this keyword

Posted by greatstar00 on Fri, 29 Nov 2019 00:26:35 +0100

Re learn java-9. Preliminary understanding of this keyword

Preliminary understanding of this keyword

Call properties of this class

for instance:

class Emp {
	private int id;
	private String name;
	private double sal;
	private String dept;
//The most commonly used is to use this to represent this type of attribute, for example, this.id=id to assign the parameter id in the method to the parameter id in the class.
	public Emp(int id, String name, double sal, String dept) {
		this.id = id;
		this.name = name;
		this.sal = sal;
		this.dept = dept;
	}
}

Call ordinary methods of this class

for instance:

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();//Call this type of method
	}
	public String getInfo() {
		return "id: "+ id +" name: "+ name + " sal: " + sal + " dept: " + dept;
	}
}

Call constructor

For example, write out all the construction methods with four parameters.

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");
	}
	//The first three constructors call the fourth constructor, which saves a lot of duplicate code
	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;
	}
}

Note: when calling this type of method with this, be sure to keep the exit, otherwise infinite recursion will occur.

Represents the current object

for instance:

class Emp {
	private int id;
	private String name;
	private double sal;
	private String dept;
	
	public Emp getInfo() {
		return this;//Object returned
	}
}

Test code:

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

Output results:

As you can see, the memory referred to by this is consistent with the object entity that called the method.

Topics: Java Attribute