English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
OverloadingIt is a mechanism for achieving polymorphism, where a class contains two methods with the same name and different parameters.
No matter when this method is called, the method body will be bound to the method call based on the parameters.
Similar to methods, you can also overload constructors, that is, you can write multiple constructors with different parameters.
And, based on the parameters passed at instantiation, the corresponding constructor will be called.
public class Sample{ public Sample(){ System.out.println("Hello how are you"); } public Sample(String data){ System.out.println(data); } public static void main(String args[]){ Sample obj = new Sample("Tutorialspoint"); } }
Output Result
Tutorialspoint
Just like a regular constructor, you can also override the enumeration's constructor. That is, you can make the constructor have different parameters.
The following Java program demonstrates constructor overloading in enumerations.
import java.util.Arrays; enum Student { Krishna("Krishna", "kasyap", "Bhagavatula"), Ravi("Ravi", "Kumar", "pyda"), Archana("Archana", "devraj", "mohonthy"); private String firstName; private String lastName; private String middleName; private Student(String firstName, String lastName, String middlename){ this.firstName = firstName; this.lastName = lastName; this.middleName = middleName; } private Student(String name) { this(name.split(" ")[0], name.split(" ")[1], name.split(" ")[2]), } } public class ConstructorOverloading{ public static void main(String args[]) { Student stds[] = Student.values(); System.out.println(Arrays.toString(stds)); } }
Output Result
[Krishna, Ravi, Archana]