Java this keyword Invoking Overloaded Constructors

Introduction

We can invoke overloaded constructors via this keyword.

The general form is shown here:

this(arg-list) 
class MyClass { /*  w  ww .  jav a2 s .c  om*/
  int a; 
  int b; 
 
  // initialize a and b individually 
  MyClass(int i, int j) { 
    a = i; 
    b = j; 
    System.out.println("MyClass(int i, int j)");
  } 
 
  // initialize a and b to the same value 
  MyClass(int i) { 
    this(i, i); // invokes MyClass(i, i)
    System.out.println("MyClass(int i)");
  } 
 
  // give a and b default values of 0 
  MyClass() { 
    this(0); // invokes MyClass(0) 
    System.out.println("MyClass() ");
  } 
}

public class Main {
  public static void main(String args[]) {
    MyClass m = new MyClass();
    
  }
}



PreviousNext

Related