Constructor overloading in enumerations in Java.

Java 8Object Oriented ProgrammingProgramming

Overloading is a one of the mechanisms to achieve polymorphism where, a class contains two methods with same name and different parameters.

Whenever you call this method the method body will be bound with the method call based on the parameters.

Constructor overloading

Similar to methods you can also overload constructors i.e. you can write more than constructor with different parameters.

And, based on the parameters we pass at the time of instantiation, respective constructor will be invoked.

Example

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

Tutorialspoint

Constructor overloading in enum

Just like normal constructors you can also override the constructors of an enum. i.e. you can have the constructor with different parameters.

Example

Following Java program demonstrates the 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

[Krishna, Ravi, Archana]
raja
Published on 05-Aug-2019 18:04:08
Advertisements