ThisKeyword.java
package thiskeyword; public class ThisKeyword { public static void main(String[] args) { FunObject f1 = new FunObject(); FunObject f2 = new FunObject(2,3); } }
FunObject.java
package thiskeyword; public class FunObject { int a = 20; int b = 30; int c = 50; // constructors public FunObject(){ System.out.println( a + " " + b + " " +c); } public FunObject(int a, int b){ this.a=a; this.b=b; System.out.println( a + " " + b + " " +c); } }
Outputs:
20 30 50
2 3 50
The THIS keyword allows us to distinguish between the variables of the class, and the variables being passed to the constructor during object creation.
If we add the line
this();
to the code above (complete code below)
package thiskeyword; public class FunObject { int a = 20; int b = 30; int c = 50; // constructors public FunObject(){ System.out.println( a + " " + b + " " +c); } public FunObject(int a, int b){ this(); // WE JUST ADDED THIS LINE ///////////////// this.a=a; this.b=b; System.out.println( a + " " + b + " " +c); } }
We get output:
20 30 50
20 30 50
2 3 50
the this() line is saying, “the object that called me, this, has no constructor, so it called the constructor with no arguments above.
If we do the following and add this(2000,3000) to our funObject
package thiskeyword; public class FunObject { int a = 20; int b = 30; int c = 50; // constructors public FunObject(){ this(2000,3000); // calls the contractor of the class // we're already in. HAS to be on first line of constructor. System.out.println( a + " - " + b + " " +c); } public FunObject(int a, int b){ this.a=a; this.b=b; System.out.println( a + " " + b + " " +c); } }
Output:
2000 3000 50
2000 – 3000 50
2 3 50