Website For Developers

Constructor overloading in Java



1#Example of constructor overloading in Java

public class HelloWorld {

   HelloWorld() {
     System.out.println( "This is Default Constructor." );
   }
   HelloWorld (int a, int b) {
     System.out.println(a+b);
   }

   public static void main(String[] args) {
     HelloWorld obj1 = new HelloWorld();
     HelloWorld obj2 = new HelloWorld(25 , 25);
   }
}

Output

This is Default Constructor.
50


2#Example of constructor overloading in Java

public class ConstructorOverloading {

   // Constructor with 2 integer parameters
   ConstructorOverloading (int a, int b) {
     System.out.println(a+b);
   }

   // Constructor with 2 String parameters
   ConstructorOverloading (String a, String b) {
     System.out.println(a+b);
   }

   public static void main(String[] args) {
     ConstructorOverloading obj1 = new ConstructorOverloading (10 , 20); //obj with integer
     ConstructorOverloading obj2 = new ConstructorOverloading ("Hello", "World"); //obj with String
   }
}

Output

30
HelloWorld