R
Roedy Green
I have written enum code that works, but suddenly I had a sinking
feeling that it has no business working. I did a little disassembling
and sorted out the mystery.
let's say I create an enum with method next().
Then I override the next() method with custom code in the various
enum constants.
These methods live in anonymous inner classes of the enum (though
oddly they decompile as static).
Then I do something like this:
Breed d = Breed.DALMATIAN;
d.next();
How on earth does Java know to use DALMATIAN.next() rather than
Breed.next()?
The answer is that d contains a reference to the DALMATIAN inner class
that EXTENDS the Breed enum class as well as being an inner class of
it. So the next() method overrides the one in the Breed class.
feeling that it has no business working. I did a little disassembling
and sorted out the mystery.
let's say I create an enum with method next().
Then I override the next() method with custom code in the various
enum constants.
These methods live in anonymous inner classes of the enum (though
oddly they decompile as static).
Then I do something like this:
Breed d = Breed.DALMATIAN;
d.next();
How on earth does Java know to use DALMATIAN.next() rather than
Breed.next()?
The answer is that d contains a reference to the DALMATIAN inner class
that EXTENDS the Breed enum class as well as being an inner class of
it. So the next() method overrides the one in the Breed class.