Skip to content

Instantly share code, notes, and snippets.

@bikashdaga
Created March 3, 2022 10:46
Show Gist options
  • Save bikashdaga/c2d9d4bef904b35d9e4bc962c3a7d942 to your computer and use it in GitHub Desktop.
Save bikashdaga/c2d9d4bef904b35d9e4bc962c3a7d942 to your computer and use it in GitHub Desktop.
Constructor Overloading in Java
Input:
public class ConstructorEG {
String name;
Integer number;
ConstructorEG(){ // default constructor
System.out.println("Default Constructor called");
}
ConstructorEG(String defaultValue){ // parameterised constructor 1
System.out.println("Parameterized Constructor for name called");
name = defaultValue;
}
ConstructorEG(Integer number){ // parameterised constructor 2
System.out.println("Parameterized Constructor for number called");
this.number = number;
}
public static void main(String[] args) {
ConstructorEG object = new ConstructorEG("custom value");
System.out.println(object.name);
ConstructorEG object2 = new ConstructorEG(123);
System.out.println(object2.number);
}
}
Output:
Parameterized Constructor for name called
custom value
Parameterized Constructor for number called
123
@bikashdaga
Copy link
Author

Constructor overloading in Java 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.

To know more about Constructor Overloading read this article on Scaler Topic.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment