1. The This keyword in Java represents the object itself. Use the This keyword to invoke properties and methods inside the class, which makes the code more readable because it clearly indicates the source of the property or method.
2. Other constructors in this class can also be called using the This keyword in the constructor, but there are a few things to note:
- The constructor calls the other constructors and needs to write this on the first line of the constructor.
- The constructor is not recursive and prevents a dead loop.
3. The constructors of a class are divided into non-parametric and parametric constructors. It is common practice to specify that you write a constructor that contains all the fields, and then other constructors can call the function directly to implement code reuse.
Packageorg.lyk.entities; Public classEmpImplementsComparable<emp>{ Private Longempno; PrivateString ename; PrivateString Job; Private floatSal; Public LongGetempno () {returnempno; } Public voidSetempno (Longempno) { This. empno =empno; } PublicString Getename () {returnename; } Public voidsetename (String ename) { This. ename =ename; } PublicString getjob () {returnjob; } Public voidsetjob (String job) { This. Job =job; } Public floatgetsal () {returnSal; } Public voidSetsal (floatSal) { This. Sal =Sal; } @Override PublicString toString () {return"Emp [empno=" + Empno + ", ename=" + ename + ", job=" + Job + ", sal=" + sal + "]"; } PublicEmp () { This(-1, "Anonymous", "unspecified", 0); } PublicEMP (Longempno) { This(Empno, "Anonymous", "unspecified", 0); } PublicEMP (Longempno, String name) { This(Empno, name, "unspecified", 0); } PublicEMP (LongEmpno, String ename, String job,floatSal) { Super(); This. empno =empno; This. ename =ename; This. Job =job; This. Sal =Sal; } @Override Public intcompareTo (Emp o) {if( This. Sal <o.sal)return-1; Else if( This. Sal >o.sal)return1; if( This. empno <o.empno)return-1; Else if( This. empno >o.empno)return1; return0; } }
PackageOrg.lyk.main;Importorg.lyk.entities.Emp; Public classmain{ Public Static voidMain (string[] args) {emp[] Emp=NewEmp[4]; emp[0] =NewEmp (); emp[1] =NewEMP (9989); emp[2] =NewEMP (9987, "Jerry"); emp[3] =NewEMP (7786, "Larry", "Programer", 889); Java.util.Arrays.sort (EMP); for(Emp item:emp) {System.out.println (item); } }}
The use of the This keyword in the constructor method in Java