Enhancing the Grade Enum


The number of basic grade points is information that can be associated directly with the Grade enum. It is possible to enhance the definition of an enum to include instance variables, constructors, and methods, just like any other class type. The main restriction is that you cannot extend an enum from another enum.

Modify the declaration of the Grade enum in the Student class:

 public class Student {    public enum Grade {       A(4),       B(3),       C(2),       D(1),       F(0);       private int points;       Grade(int points) {          this.points = points;       }       int getPoints() {          return points;       }    }    ... 

You have now associated each named instance of the enum with a parameter. Further, you terminated the list of enum instances with a semicolon. After that semicolon, code in the Grade enum declaration looks just like that in any class type. The parameter associated with each named enum instance is passed to the constructor of Grade. This points parameter is stored in an instance variable named points. You retrieve the points via the getPoints method.

You can now simplify the code in BasicGradingStrategy to:

 package sis.studentinfo; public class BasicGradingStrategy implements GradingStrategy {    public int getGradePointsFor(Student.Grade grade) {       return grade.getPoints();    } } 

No more switch statement!



Agile Java. Crafting Code with Test-Driven Development
Agile Javaв„ў: Crafting Code with Test-Driven Development
ISBN: 0131482394
EAN: 2147483647
Year: 2003
Pages: 391
Authors: Jeff Langr

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net