Can an enum extend another class in Java?

No, an enum cannot extend another class in Java. Every enum automatically inherits from the java.lang.Enum class, and since Java allows a class to extend only one parent class, an enum cannot extend any additional class. However, enums can implement one or more interfaces, which allows them to define custom behavior while still representing a fixed set of constants.

Key Points:

• All enums implicitly extend java.lang.Enum. • Java does not support multiple class inheritance, so enums cannot extend any other class. • Enums can implement interfaces to provide additional functionality. • Enum constants can have fields, methods, and constructors. • Using interfaces with enums is the recommended way to add behavior.

Example:

Consider an application with different payment methods. An enum can implement a Payment interface to provide different payment processing logic for each constant, even though it cannot extend a Payment class.

Code Example:

interface Payment {
    void process();
}

enum PaymentType implements Payment {

    CREDIT_CARD {
        @Override
        public void process() {
            System.out.println("Processing Credit Card Payment");
        }
    },

    UPI {
        @Override
        public void process() {
            System.out.println("Processing UPI Payment");
        }
    };
}

public class Main {
    public static void main(String[] args) {
        PaymentType.UPI.process();
    }
}

Interview Tip:

A concise interview answer is: "No, an enum cannot extend another class because it already extends java.lang.Enum implicitly. Since Java supports only single inheritance for classes, extending another class is not possible. However, enums can implement interfaces to achieve additional behavior."