Java enumeration abstract method combat

Demand background

   Demand has identified several fixed constant value, and each has a constant value of the same behavior, but the specific implementation details are different. Abstract methods recommended enumerated advantages: clear structure, easy to extend.

Enum class implements the abstract methods

   As with conventional abstract class, enum class allows us to define its abstract method, then each enumeration instance to implement this method in order to produce different behavior, pay attention to the abstract keyword for enumeration class is not necessary, For chestnut:

public  enum GradeEnum {
     // test scores is divided into A, B, C, D and E are five levels 
    A ( "90 ~ 100" ) { 
        @Override 
        public String getGrade (String studentName) {
             return studentName + "excellent" ; 
        } 
    } , B ( "80 ~ 89" ) { 
        @Override 
        public String getGrade (String studentName) {
             return studentName + "good" ; 
        } 
    }, C ( "70 ~ 79" ) { 
        @Override 
        public String getGrade (String studentName) {
             return studentName + "medium"+ getScore();
        }
    }, D("60~69") {
        @Override
        public String getGrade(String studentName) {
            return studentName + "及格";
        }
    }, E("0~59") {
        @Override
        public String getGrade(String studentName) {
            return studentName + "成绩很差";
        }
    };
    private String score;

    private GradeEnum(String score) {
        this.score = score;
    }

    public String getScore() {
        return this.score;
    }

    public abstract String getGrade(String studentName);
}

   Defined GradeEnum time, did not add the abstract keyword.

   Enum class can be seen as a normal class, enum class can define properties and methods, except that: enum can not use extends keyword to inherit other classes, because enum has inherited java.lang.Enum (java It is a single inheritance). 

   The method can operate directly members member variables, such as Score, and returns the obtained result, each static instance by walking its member variables to return calculation result obtained, are calculated according to the method procedure member properties.

If we want each instance has a completely different way to achieve, does not rely on member variables, then you need to define abstract methods, examples of the use of anonymous {...} block implementation of the abstract in an anonymous block. The abstract method in the above example getGrade. To achieve the same purpose may be achieved by enumeration class interfaces.

 

Guess you like

Origin www.cnblogs.com/east7/p/11827810.html