Created
March 3, 2022 10:46
-
-
Save bikashdaga/c2d9d4bef904b35d9e4bc962c3a7d942 to your computer and use it in GitHub Desktop.
Constructor Overloading in Java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.