×

Java Programs

Java Practice

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 statement

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.

Java program to create an enum class with constructor and method

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 »





Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.