Question:
How to use the keyword this in a constructor?
Answer:
From within a constructor, you can also use the this keyword to call another constructor in the same class. Doing so is called an explicit constructor invocation.
Code:
public class MyClass { int a=0; int b=0; MyClass(){ this(5,8); } MyClass(int a, int b){ this.a = a; this.b = b; } public static void main(String[] args) { MyClass mc = new MyClass(); System.out.println("mc.a: " + mc.a); System.out.println("mc.b: " + mc.b); } }
Output:
$ java MyClass mc.a: 5 mc.b: 8