Abstract Classes


You could stop here and have a sufficient solution. You could also go one step further and eliminate a bit more duplication by having the superclass BasicGradingStrategy implement the GradingStrategy interface directly. The only problem is, you don't necessarily have an implementation for getGradePointsFor.

Java allows you to define a method as abstract, meaning that you cannot or do not wish to supply an implementation for it. Once a class contains at least one abstract method, the class itself must similarly be defined as abstract. You cannot create new instances of an abstract class, much as you cannot directly instantiate an interface.

Any class extending from an abstract class must either implement all inherited abstract methods, otherwise it too must be declared as abstract.

Change the declaration of BasicGradingStrategy to implement the GradingStrategy interface. Then supply an abstract declaration for the getGradePointsFor method:

 package sis.studentinfo; abstract public class BasicGradingStrategy implements GradingStrategy {    abstract public int getGradePointsFor(Student.Grade grade);    int basicGradePointsFor(Student.Grade grade) {       switch (grade) {          case A: return 4;          case B: return 3;          case C: return 2;          case D: return 1;          default: return 0;       }    } } 

The subclasses no longer need to declare that they implement the GradingStrategy interface:

 // HonorsGradingStrategy.java package sis.studentinfo; public class HonorsGradingStrategy extends BasicGradingStrategy {    public int getGradePointsFor(Student.Grade grade) {       int points = basicGradePointsFor(grade);       if (points > 0)          points += 1;       return points;    } } // RegularGradingStrategy.java package sis.studentinfo; public class RegularGradingStrategy extends BasicGradingStrategy {    public int getGradePointsFor(Student.Grade grade) {       return basicGradePointsFor(grade);    } } 



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