Use enum keyword defined enumeration class to implement interface [Java]

Posted by crochk on Fri, 28 Jan 2022 02:02:20 +0100

The enum class defined by enum keyword is used to implement the interface

First of all, we need to know that the interfaces in the enumeration class implementation interfaces defined by enum keyword here are interfaces that internally declare abstract methods

The enum class defined by enum keyword can be used to implement the interface in two cases:

Case 1:

Implement the interface, and uniformly implement the abstract methods in the interface in the enumeration class

  • For case 1, the methods in the interface are uniformly implemented in the class. At this time, all enumeration class objects execute the unified method when executing the methods in the interface

Case 2:

Implement the interface, and let each object of the enumeration class implement the abstract methods in the interface respectively

  • For case 2, the method in the interface allows each object to be implemented separately. There is no unified implementation of the abstract method in the interface. At this time, the abstract method in the interface called by which object will be used, and the method rewritten by which object will be called

Note: mode 2 is only applicable to enumeration classes defined by enum keyword. If it is user-defined enumeration class, it is not applicable

Here we use examples to understand the difference between situation 1 and situation 2

1. The first is situation 1

  • Let's give the interface first
package Enumeration class.Definition of enumeration class.enum Keyword definition enumeration class;

public interface Info {
    //public abstract is omitted 
    void show();
}
  • Then we give the usage and implement the enumeration class of the interface in one way
package Enumeration class.Definition of enumeration class.enum Keyword definition enumeration class;


//Define enumeration class through enum keyword
public enum Season2 implements Info{
    /*
    1. When defining an enum class through enum keyword, we first need to provide the object of the current enum class. Multiple objects are separated by (comma) and the end object is used; (end of seal)

    Note: many unimportant things are omitted when creating objects here, such as new keyword, variable type and constructor name
    Add: if the object is created with a parameterless constructor, then () can also be omitted

     */
    SPRING("spring","in the warm spring , flowers are coming out with a rush"),
    SUMMER("summer","Summer heat"),
    AUTUMN("autumn","fresh autumn weather"),
    WINTER("winter","a world of ice and snow");

    /*
    The following steps are the same as when we customize the enumeration class
     */

    /*
    2. Declare the attribute (constant) of the Season1 class, and use the private final keyword to decorate it
     */
    private final String seasonName;
    private final String seasonDesc;

    /*
    3. Privatize the constructor of the class and assign values to the properties of the object

    Note: using constructor assignment can make each of our objects have a unique constant
     */
    private Season2(String seasonName , String seasonDesc){
        this.seasonName = seasonName;
        this.seasonDesc = seasonDesc;
    }

    /*
    4. Other demands:
    4.1 Gets the properties of the enumeration class object
     */
    public String getSeasonName(){
        return this.seasonName;
    }
    public String getSeasonDesc(){
        return this.seasonDesc;
    }

    /*
    4.2 Provide the toString() method according to the requirements

    Note: even if we do not override the toString() method here, we will not output the address value when outputting this enumeration class object, because the enumeration classes defined with enum keyword are directly inherited
    java.lang.Enum Class, and the Enum class rewrites the toString() method inherited from the Object class. The output of the toString() method rewritten in the Enum class is the constant name corresponding to the enumeration class Object
     */
    @Override
    public String toString() {
        return "Season1{" +
                "seasonName='" + seasonName + '\'' +
                ", seasonDesc='" + seasonDesc + '\'' +
                '}';
    }
    //The show() method in the overridden interface
    @Override
    public void show(){
        System.out.println("This is a season!");
    }
}
//Test of enumeration classes defined with enum keyword
class Season2Test{
    public static void main(String[] args) {
        //Gets the object of the enumeration class
        Season2 spring = Season2.SPRING;
        //Call the show() method. At this time, no matter which enumeration class object we use to call this method, it will output: This is a season!
        spring.show();
    }
}

2. Then case 2

  • Let's also give the interface first
    • Both interfaces are the same interface
package Enumeration class.Definition of enumeration class.enum Keyword definition enumeration class;

public interface Info {
    //public abstract is omitted 
    void show();
}
  • Then we give the enumeration class that implements this interface in case 2
package Enumeration class.Definition of enumeration class.enum Keyword definition enumeration class;


//Define enumeration class through enum keyword
public enum Season3 implements Info{
    /*
    1. When defining an enum class through enum keyword, we first need to provide the object of the current enum class. Multiple objects are separated by (comma) and the end object is used; (end of seal)

    Note: many unimportant things are omitted when creating objects here, such as new keyword, variable type and constructor name
    Add: if the object is created with a parameterless constructor, then () can also be omitted

     */
    
    //Note that here we override the abstract methods in the interface for each object
    SPRING("spring","in the warm spring , flowers are coming out with a rush"){
        @Override
        public void show(){
            System.out.println("Where is spring?");
        }
    },
    SUMMER("summer","Summer heat"){
        @Override
        public void show(){
            System.out.println("Where is summer?");
        }
    },
    AUTUMN("autumn","fresh autumn weather"){
        @Override
        public void show(){
            System.out.println("Where is summer?");
        }
    },
    WINTER("winter","a world of ice and snow"){
        @Override
        public void show(){
            System.out.println("Where is summer?");
        }
    };

    /*
    The following steps are the same as when we customize the enumeration class
     */

    /*
    2. Declare the attribute (constant) of the Season1 class, and use the private final keyword to decorate it
     */
    private final String seasonName;
    private final String seasonDesc;

    /*
    3. Privatize the constructor of the class and assign values to the properties of the object

    Note: using constructor assignment can make each of our objects have a unique constant
     */
    private Season3(String seasonName , String seasonDesc){
        this.seasonName = seasonName;
        this.seasonDesc = seasonDesc;
    }

    /*
    4. Other demands:
    4.1 Gets the properties of the enumeration class object
     */
    public String getSeasonName(){
        return this.seasonName;
    }
    public String getSeasonDesc(){
        return this.seasonDesc;
    }

    /*
    4.2 Provide the toString() method according to the requirements

    Note: even if we do not override the toString() method here, we will not output the address value when outputting this enumeration class object, because the enumeration classes defined with enum keyword are directly inherited
    java.lang.Enum Class, and the Enum class rewrites the toString() method inherited from the Object class. The output of the toString() method rewritten in the Enum class is the constant name corresponding to the enumeration class Object
     */
    @Override
    public String toString() {
        return "Season1{" +
                "seasonName='" + seasonName + '\'' +
                ", seasonDesc='" + seasonDesc + '\'' +
                '}';
    }
}
//Test of enumeration classes defined with enum keyword
class Season3Test{
    public static void main(String[] args) {
        //Gets the object of the enumeration class
        Season3 spring = Season3.SPRING;
        //Call the show() method. At this time, calling the show() method with different objects will have different results, because the abstract methods in the interface are rewritten in each object
        spring.show();
    }
}

Summary:

1. Only the enumeration class can rewrite the abstract method in the interface for each object after implementing the interface, instead of implementing it in the enumeration class

  • So why can enumeration classes and other classes not?
    • Because the method defined in the interface that must be rewritten defines a non static method, and the caller of the non static method is an object. If it is an ordinary class, we can create objects infinitely. We can't let unlimited objects rewrite the methods in the interface, so we can only rewrite them uniformly in the class, All objects of this ordinary class use this rewritten method - but enumeration classes are different. When enumerating objects of a class, the number of objects of the enumeration class is given (the number of objects of the enumeration class is determined, and each object is also determined and immutable), so we can let a limited number of objects of the enumeration class implement the abstract methods in the interface respectively

Topics: Java Back-end