Q:

Java program to create an enum class with constructor and method

belongs to collection: Java Enums Programs

0

Java program to create an enum class with constructor and method

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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().

 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

<< Java program to access enum constants using \'...