Re: Why Generics?
- From: "Chris Uppal" <chris.uppal@xxxxxxxxxxxxxxxxxxxxxxxxxxx>
- Date: Wed, 25 May 2005 18:14:09 +0100
I wrote:
> OTOH, if you use your own implementation of the type-safe enum pattern,
> then their object-nature is not hidden by the compiler and so you can use
> polymorphism to avoid having to use switch statements in the first place.
I must correct myself. It /is/ possible to define methods against enums
(considered as a special kind of class). I'm not sure how I missed it, but
miss it I did.
The documentation that ships with JDK1.5.0 has a few examples, one shows that
enums can have their own methods (and data too though that's not shown here):
==============
public enum Operation {
PLUS, MINUS, TIMES, DIVIDE;
// Do arithmetic op represented by this constant
double eval(double x, double y){
switch(this) {
case PLUS: return x + y;
case MINUS: return x - y;
case TIMES: return x * y;
case DIVIDE: return x / y;
}
throw new AssertionError("Unknown op: " + this);
}
}
==============
Another demonstrates so-called 'constant specific methods':
==============
public enum Operation {
PLUS { double eval(double x, double y) { return x + y; } },
MINUS { double eval(double x, double y) { return x - y; } },
TIMES { double eval(double x, double y) { return x * y; } },
DIVIDE { double eval(double x, double y) { return x / y; } };
// Do arithmetic op represented by this constant
abstract double eval(double x, double y);
}
==============
-- chris
.
- References:
- Why Generics?
- From: David Blickstein
- Re: Why Generics?
- From: Eric Sosman
- Re: Why Generics?
- From: Chris Uppal
- Re: Why Generics?
- From: Mike Schilling
- Re: Why Generics?
- From: Chris Uppal
- Re: Why Generics?
- From: David Blickstein
- Re: Why Generics?
- From: David Blickstein
- Re: Why Generics?
- From: Dale King
- Re: Why Generics?
- From: Chris Uppal
- Why Generics?
- Prev by Date: Re: Newbie: Just drop it on the classpath
- Next by Date: Re: Why Generics?
- Previous by thread: Re: Why Generics?
- Next by thread: Re: Why Generics?
- Index(es):
Relevant Pages
|