The easiest way, I suppose, is using the constructor.
class Fruit{
private final String name;
public Fruit(String name){
if (/* name has an incorrect value, is null or whatever */)
throw new IllegalArgumentException("name");
this.name = name;
}
}
//Apple wants to get an error if it does not use the name variable
class Apple extends Fruit {
public Apple(){ super("Apple"); }
}
Now it's impossible to make a Fruit
subclass which doesn't pass a name to the Fruit
constructor. By making the field final
, you also get the added bonus that once the field has been set to a proper value, subclasses can't put bogus stuff there (except for using reflection etc, but then all bets are off).
Edit: Also, as pointed out by more attentive posters, you don't implement
classes, you extend
them. For interfaces (which you do implement
), you can't enforce that sane values are returned from the methods (not in any easy way - I suppose you could use AOP to check the return values and throw an IllegalStateException
when bogus values are returned).