ADVERTISEMENT
ADVERTISEMENT

Java program to create an enum class with constructor and method

Java example to create an enum class with constructor and method.
Submitted by Nidhi, on April 04, 2022

Problem Solution:

In this program, we will create an enum class that contains constructor and method. Here, we will also create a class Main. Then we will create an object of enum class and call its constructor and method.

Program/Source Code:

The source code to create an enum class with constructor and method is given below. The given program is compiled and executed successfully.

// Java program to create an enum class 
// with constructor and method

enum Vehicle {
  BIKE,
  CAR,
  BUS;

  private Vehicle() {
    System.out.println("Constructor called for : " + this.toString());
  }

  public void vehicleMethod() {
    System.out.println("Vehicle is running.");
  }
}

public class Main {
  public static void main(String[] args) {
    Vehicle veh = Vehicle.BUS;
    veh.vehicleMethod();
  }
}

Output:

Constructor called for : BIKE
Constructor called for : CAR
Constructor called for : BUS
Vehicle is running.

Explanation:

In the above program, we created an enum class Vehicle and a public class Main. The enum class Vehicle contains a constructor and a method.

The Main class contains a method main(). The main() method is an entry point for the program. Here, we created the object of the Vehicle enum class and called its constructor for each enum constant and also called the method vehicleMethod().

Java Enums Programs »


ADVERTISEMENT
ADVERTISEMENT


Comments and Discussions!



ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.