Java Programming Enumerations And Interfaces Complete Guide

 Last Update:2025-06-23T00:00:00     .NET School AI Teacher - SELECT ANY TEXT TO EXPLANATION.    7 mins read      Difficulty-Level: beginner

Understanding the Core Concepts of Java Programming Enumerations and Interfaces

Java Programming: Enumerations and Interfaces

Enumerations

Declaring an Enumeration: To declare an enum in Java, you need to use the enum keyword followed by the name of the enum. Each enum constant is separated by a comma.

public enum Day {
    SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY
}

Using Enumerations: You can use enums just like any other data type in Java. They can be assigned to variables, passed as arguments to methods, and can be used in switch-case statements.

public class EnumExample {
    Day day;  
    public EnumExample(Day day) {
        this.day = day;
    }

    public void tellItLikeItIs() {
        switch (day) {
            case MONDAY:
                System.out.println("Mondays are blue.");
                break;
            case FRIDAY:
                System.out.println("Fridays are better.");
                break;
            case SATURDAY:
            case SUNDAY:
                System.out.println("Weekends are best.");
                break;
            default:
                System.out.println("Midweek days are so-so.");
                break;
        }
    }
}

public static void main(String[] args) {
    EnumExample firstDay = new EnumExample(Day.MONDAY);
    firstDay.tellItLikeItIs();
    EnumExample thirdDay = new EnumExample(Day.WEDNESDAY);
    thirdDay.tellItLikeItIs();
    EnumExample fifthDay = new EnumExample(Day.FRIDAY);
    fifthDay.tellItLikeItIs();
    EnumExample sixthDay = new EnumExample(Day.SATURDAY);
    sixthDay.tellItLikeItIs();
    EnumExample seventhDay = new EnumExample(Day.SUNDAY);
    seventhDay.tellItLikeItIs();
}

Enum Methods and Fields: Enums can also have instance fields, constructors, and methods. Unlike static constants, enums can maintain separate copies of enum constants and are more powerful.

public enum Planet {
    MERCURY (3.303e+23, 2.4397e6),
    VENUS   (4.869e+24, 6.0518e6),
    EARTH   (5.976e+24, 6.37814e6),
    MARS    (6.421e+23, 3.3972e6),
    JUPITER (1.9e+27,   7.1492e7),
    SATURN  (5.688e+26, 6.0268e7),
    URANUS  (8.686e+25, 2.5559e7),
    NEPTUNE (1.024e+26, 2.4746e7);

    private final double mass;   // in kilograms
    private final double radius; // in meters

    Planet(double mass, double radius) {
        this.mass = mass;
        this.radius = radius;
    }

    public double mass() { return mass; }
    public double radius() { return radius; }

    // universal gravitational constant  (m3 kg-1 s-2)
    public static final double G = 6.67300E-11;

    public double surfaceGravity() {
        return G * mass / (radius * radius);
    }

    public double surfaceWeight(double otherMass) {
        return otherMass * surfaceGravity();
    }
}

Enum Utility Methods: Java enums come with several utility methods.

  • values(): Returns an array containing all the values of the enum.
  • valueOf(String name): Returns the enum constant of the specified string value.
  • ordinal(): Returns the ordinal (position in declaration) of this enum constant.

Interfaces

Interfaces in Java are used to support the concept of Multiple Inheritance. An interface in Java is a reference type, similar to a class, that can contain only constants, method signatures, default methods, static methods, and nested types. Interfaces cannot contain instance fields. The methods in interfaces are abstract by default.

Declaring an Interface: To declare an interface, use the interface keyword and then the name of the interface.

interface Animal {
    void eat();
    void travel();
}

Implementing an Interface: A class implements an interface, thereby inheriting the abstract methods of the interface.

public class MammalInt implements Animal {

    @Override
    public void eat() {
        System.out.println("Mammal eats");
    }

    @Override
    public void travel() {
        System.out.println("Mammal travels");
    } 

    public int numberOfLegs() {
        return 4;
    }

    public static void main(String args[]) {
        MammalInt m = new MammalInt();
        m.eat();
        m.travel();
    } 
}

Interface Methods:

  • Abstract Methods: Traditional interface methods that do not have an implementation. Each class that implements the interface must implement every method declared without an implementation.
  • Default Methods: Introduced in Java 8, default methods have an implementation and can be overridden by a class implementing the interface.
  • Static Methods: Introduced in Java 8, static methods are defined in an interface and can be accessed directly by the interface name, without creating an instance of the interface.
  • Private Methods: Introduced in Java 9, private methods can only be used by default or static methods of the same interface.
interface Vehicle {
    // Abstract method
    void start();

    // Default method
    default void stop() {
        System.out.println("Vehicle stops");
    }

    // Static method
    static void honk() {
        System.out.println("Honk honk");
    }

    // Private method
    private void checkValve() {
        System.out.println("Checking valve");
    }
}

Multiple Interfaces: A class can implement multiple interfaces, which provides for multiple inheritance. Interfaces can extend other interfaces, and classes can implement multiple interfaces simultaneously.

References:

Online Code run

🔔 Note: Select your programming language to check or run code at

💻 Run Code Compiler

Step-by-Step Guide: How to Implement Java Programming Enumerations and Interfaces

Example 1: Java Enumerations

Topic: Creating and Using An Enum in Java

Step 1: Understand What An Enumeration Is

An Enum in Java is a special data type that enables a variable to be a set of predefined constants. The keyword enum is used to declare an enum in Java.

Step 2: Create A Simple Enum

Let's create an enum called Day which represents the days of the week.

public enum Day {
    SUNDAY,
    MONDAY,
    TUESDAY,
    WEDNESDAY,
    THURSDAY,
    FRIDAY,
    SATURDAY
}

In this code, the enum Day declaration defines an enumerated type named Day. Seven constants (SUNDAY through SATURDAY) are defined for that type.

Step 3: Use The Enum In Your Code

Here is how you can use the Day enum inside a class.

public class WeekdayExample {

    Day today;

    // Method to initialize the day
    public void setToday(Day day) {
        this.today = day;
    }

    // Method to get the current day
    public Day getToday() {
        return today;
    }

    // Method to perform activities based on the day
    public void performActivities() {
        switch(today) {
            case MONDAY:
                System.out.println("Working");
                break;
            case TUESDAY:
                System.out.println("Working");
                break;
            case WEDNESDAY:
                System.out.println("Working");
                break;
            case THURSDAY:
                System.out.println("Working");
                break;
            case FRIDAY:
                System.out.println("Working");
                break;
            case SATURDAY:
                System.out.println("Resting");
                break;
            case SUNDAY:
                System.out.println("Resting");
                break;
        }
    }

    public static void main(String[] args) {
        WeekdayExample example = new WeekdayExample();
        example.setToday(Day.MONDAY);
       (example.getToday());
        example.performActivities();

        example.setToday(Day.SATURDAY);
        example.performActivities();
    }
}

Step 4: Run The Code

When you run this code, it will print:

MONDAY
Working
SATURDAY
Resting

Example 2: Java Interfaces

Topic: Defining and Implementing An Interface in Java

Step 1: Understand What An Interface Is

An interface in Java is a reference type, similar to a class, that can contain only constants, method signatures, default methods, static methods, and nested types. Methods in interfaces are abstract by default i.e., they don't have any implementation.

Step 2: Define An Interface

Let's define an interface called Animal which has one method makeSound.

public interface Animal {
    void makeSound(); // Abstract method (does not have a body)
}

Step 3: Implement The Interface

Next, we create a class called Dog that implements the Animal interface.

public class Dog implements Animal {

    @Override
    public void makeSound() {
        // The body of makeSound() is provided here
        System.out.println("Bark");
    }

    // Other dog-specific fields and methods can be added here
}

Then, we create another class called Cat which also implements the Animal interface.

public class Cat implements Animal {

    @Override
    public void makeSound() {
        // The body of makeSound() is provided here
        System.out.println("Meow");
    }

    // Other cat-specific fields and methods can be added here
}

Step 4: Using Objects That Implement The Interface

Now, let’s write a simple main method to use a Dog and a Cat.

public class AnimalExample {

    public static void main(String[] args) {
        Animal myDog = new Dog(); // Declare interface variable and assign it to a Dog object
        Animal myCat = new Cat(); // Declare interface variable and assign it to a Cat object

        myDog.makeSound(); // Call the makeSound() method on the dog object
        myCat.makeSound(); // Call the makeSound() method on the cat object

        // Alternatively, using instanceof operator to check the actual object type
        if (myDog instanceof Dog){
            System.out.println("myDog is a dog object.");
        } else {
            System.out.println("myDog is not a dog object.");
        }

        if (myCat instanceof Cat){
            System.out.println("myCat is a cat object.");
        } else {
            System.out.println("myCat is not a cat object.");
        }
    }
}

Step 5: Run The Code

When you run this code, it will print:

Top 10 Interview Questions & Answers on Java Programming Enumerations and Interfaces

Java Enumerations and Interfaces: Top 10 Questions & Answers

  1. What are Enumerations in Java, and how do you define them?

    • Answer: Enumerations, often referred to as Enums, represent a group of constants. In Java, Enums are defined using the enum keyword. Each enum constant is public, static, and final.
    • Example:
      enum Day {
          SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY
      }
      
  2. Can you add methods and constructors to Enums in Java?

    • Answer: Yes, you can add constructors, methods, and variables to Enums in Java. Constructors in Enums are private by default and are implicitly static.
    • Example:
      enum Planet {
          MERCURY(3.303e+23, 2.4397e6),
          VENUS(4.869e+24, 6.0518e6);
      
          private final double mass;   // in kilograms
          private final double radius; // in meters
      
          Planet(double mass, double radius) {
              this.mass = mass;
              this.radius = radius;
          }
      
          double mass() { return mass; }
          double radius() { return radius; }
      }
      
  3. How do you implement an interface in an Enum in Java?

    • Answer: An Enum can implement an interface by providing implementations for the interface’s methods.
    • Example:
      interface Info {
          void displayInfo();
      }
      
      enum Season implements Info {
          WINTER {
              public void displayInfo() {
                  System.out.println("Winter season.");
              }
          },
          SPRING {
              public void displayInfo() {
                  System.out.println("Spring season.");
              }
          };
      }
      
  4. What are the differences between Enums and Interfaces in Java?

    • Answer: Enums in Java represent a fixed set of constants and can contain methods and constructors. Interfaces define a template for classes and cannot contain concrete methods (except default and static methods in Java 8+). Enums are used primarily to represent a collection of constants, whereas interfaces are used to achieve abstraction.
  5. What is the values() method in Java Enum?

    • Answer: The values() method is a static method defined in the Enum class. It returns an array containing all the constants of the Enum type in the order they are declared.
    • Example:
      for (Day day : Day.values()) {
          System.out.println(day);
      }
      
  6. Can an Enum implement multiple interfaces?

    • Answer: Yes, an Enum can implement multiple interfaces.
    • Example:
      interface Print {
          void print();
      }
      interface Show {
          void show();
      }
      
      enum Status implements Print, Show {
          SUCCESS, FAILURE;
      
          public void print() {
              System.out.println("Printing status...");
          }
      
          public void show() {
              System.out.println("Showing status...");
          }
      }
      
  7. How do you use Enum to represent a singleton pattern in Java?

    • Answer: An Enum can be used to create a singleton pattern in a simple and safe way. The Enum instance is created when the class is loaded and it is guaranteed not to be instantiated more than once.
    • Example:
      enum Singleton {
          INSTANCE;
      
          public void doSomething() {
              System.out.println("Doing something...");
          }
      }
      
  8. Can an Enum have private constructors in Java?

    • Answer: Yes, an Enum can have private constructors, and these constructors are automatically implicitly static. They are used to control the instantiation of enum constants.
    • Example:
      enum Example {
          EXAMPLE;
      
          private Example() {
              System.out.println("Constructor called...");
          }
      }
      
  9. How are Enum constants automatically static and final in Java?

    • Answer: Enum constants in Java are implicitly static, which means they belong to the Enum class itself rather than to any specific instance. They are also implicitly final to prevent subclassing and modification of these values.
    • Example:
      enum Weekday {
          MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY;
      }
      // This ensures that MONDAY, TUESDAY, ..., FRIDAY are static and final.
      
  10. What is the purpose of the ordinal() method in Java Enum?

    • Answer: The ordinal() method returns the ordinal value of the Enum constant, which represents its position in the Enum declaration, starting from 0.
    • Example:

You May Like This Related .NET Topic

Login to post a comment.