Enum constructor overloading in Java

Enum constructor overloading in Java

In Java classes, it is common to overload constructors. Enum support constructor overloading similar to any other class in java. Let us see constructor overloading with examples.

Overloading constructor with primitive datatype.

package com.code2succeed.enumtest;

public enum Country {
	USA("United States of America", 36.8),
	INDIA("India", 30.5),
	PAKISTAN("Pakistan", 33.6),
	UK("United Kingdom", 37),
	CANADA("Canada", 32);
	
	private String name;
	private double averageAge;
	private Country(String name, double averageAge) {
		this.name = name;
		this.averageAge = averageAge;
	}
	public String getName() {
		return name;
	}
	public double getAverageAge() {
		return averageAge;
	}
}
Test Class
package com.code2succeed.enumtest;

public class TestEnum {
	public static void main(String[] args) {
		Country country = Country.USA;
		System.out.println("Name of country : "+country.getName());
		System.out.println("Average Age : "+country.getAverageAge());
	}
}
Output
Name of country : United States of America
Average Age : 36.8

Overloading constructor of one Enum with other Enum.

package com.code2succeed.enumtest;

public enum City {
	NEWYORK(Country.USA),
	MUMBAI(Country.INDIA),
	DELHI(Country.INDIA),
	LONDON(Country.UK),
	ISLAMABAD(Country.PAKISTAN),
	SEATTLE(Country.USA);
	
	private Country country;
	private City(Country country) {
		this.country = country;
	}
	public Country getCountry() {
		return country;
	}
}
Test Class
package com.code2succeed.enumtest;

public class TestEnum {
	public static void main(String[] args) {
		City city = City.NEWYORK;
		System.out.println("City Name : "+city);
		System.out.println("Country Name : "+city.getCountry().getName());
	}
}
Output
City Name : NEWYORK
Country Name : United States of America

Click here to know more about Enum in Java.

Leave a Reply

Your email address will not be published. Required fields are marked *