Constructor Overloading


A constructor is just like a method but without return type. It can also be overloaded like Java methods.

Constructor overloading is a technique of having more than one constructor with different parameter lists. They are arranged in a way that each constructor performs a different task. They are differentiated by the compiler by the number of parameters in the list and their types.

Student.java (constructor overloading)
// Java program to overload constructors  
public class Student {  
  int id;  
  String name;  
  int age;  

  // The driver method
  public static void main( String args[ ] ) {
    int     no = Integer.parseInt( args[2] );
    Student s1 = new Student( 111, args[0] );
    Student s2 = new Student( 222, args[1], 25 );
    if      ( no == 2 ) s1.display( );
    else if ( no == 3 ) s2.display( );
  }

  // Two-argument constructor  
  Student( int i, String n ) {  
    id   = i;  
    name = n;  
  }  

  // Three-argument constructor  
  Student( int i, String n, int a ) {  
    id   = i;  
    name = n;  
    age  = a;  
  }

  // A member method
  void display( ) {
    System.out.println( id + " " + name + " " + age );
  }  
}
shell> java Student      (constructor argument #)

Output:           Result:




      What’s the best thing about Switzerland?    
      I don’t know, but the flag is a big plus.