Thanks miga, I did a bit more reading and now I got a much better
understanding of of the enum type with defined fields and methods.
First let me tidy up the codes to make it easier to read:
public class UsingTypeSaveEnum {
// Start of enum type
public enum FootballScore {
TOUCHDOWN(6), FIELDGOAL(3), TWOPOINTS(2), EXTRAPOINT(1);
private final int score; //attributes
FootballScore(int value) { // constructor
this.score = value;
}
public int score() { //accessor method
return score;
}
} //End enum type
...
The enum type is very good, provide you get used to reading it, enum
type with fields and method is very similar to class declaration,
except its an enum type (sounds confusing, I was confused too), it is
type safe (i.e. you cannot mix up one type with another); the private
field is final, so only accessor method applies; the way to retreive
the attributes is by referencing the accessor method like:
FootballScore.TOUCHDOWN.score().
Even though it seems like a class, by you cannot create any object
instance of it; the instances are governed by the defined enum types.
When you reference any of the types like FootballScore.TOUCHDOWN, you
are creating an instance through the constructor FootballScore(6). "6"
is the score for TOUCHDOWN
Having fields, constructor and methods in enum type seems confusing at
first; but it is exactly these features that allows it to do wonderful
things :), and its very safe too.
I am writing just to get a clear concept for myself, if it helps
anyone, it's good; if I am wrong, please let me know.
norman
On Nov 19, 5:03 pm, miga <[EMAIL PROTECTED]> wrote:
> On Nov 19, 3:06 am, "Norman Ho" <[EMAIL PROTECTED]> wrote:
>
>
>
> > Example 5.2 in Lab-1106 has the following codes for enum type:
>
> > public class UsingTypeSaveEnum {
>
> > // Note that FootballScore is now enum type
>
> > public enum FootballScore {
>
> > TOUCHDOWN(6), FIELDGOAL(3), TWOPOINTS(2), SAFETY(2),
>
> > EXTRAPOINT(1);
>
> > FootballScore(int value) {
>
> > this.score = value;
>
> > }
>
> > private final int score;
>
> > public int score() {
>
> > return score;
>
> > }
>
> > }
>
> > ...
>
> > Does the line: public enum Football ... define an inner class with enum
> > type? Or is it just defining an enum type called FootballScore?
>
> I would say both as an enum type is of class Enum, and defines
> effectively an enum type. Then inside of the enum type you may in turn
> define inner classes as you want.- Hide quoted text -
>
> - Show quoted text -
--~--~---------~--~----~------------~-------~--~----~
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at
http://groups.google.com/group/javaprogrammingwithpassion?hl=en
-~----------~----~----~----~------~----~------~--~---