开发者

A SCJP Question on topic Enums

From the SCJP Questions PDF book, I got this question..

1. enum Animals {
2. DOG("woof"开发者_StackOverflow中文版), CAT("meow"), FISH("burble");
3. String sound;
4. Animals(String s) { sound = s; }
5. }
6. class TestEnum {
7. static Animals a;
8. public static void main(String[] args) {
9. System.out.println(a.DOG.sound + " " + a.FISH.sound);
10. }
11. }

The Options are,

A. woof burble

B. Multiple compilation errors

C. Compilation fails due to an error on line 2

D. Compilation fails due to an error on line 3

E. Compilation fails due to an error on line 4

F. Compilation fails due to an error on line 9

A is the correct Answer,..

Can some body explain this..

Whether the enum can have constructors?


Enum is a class. It can have methods, constructors, fields ... as any other class.

Note that when you write DOG, CAT etc. you are naming which named instances of this enum you want to have. If they have parameteters like the sound here you have to provide appropriate constructor with parameters.


Yes, enums are allowed constructors, but only enum constants can call it. You can't add more instances of the enum. As a matter of style, the constructor(s) should be private. And of course, instance fields should generally be private, and in an enum final.

Also of note that you can get static fields and call static methods on instance expressions (even if they evaluation to null).


Yes, enums can have constructors and methods and instance variables just like other classes. But you cannot call the constructor yourself, like you would with a regular class. You can't call a= new Dog("wooooof"). The constructor will be called by the compiler for you.

This will compile fine, but on line 9, I think the compiler will warn you that you are accesing a static field in a a non-static way. Animal.DOG.sound is the "proper way" and not a.DOG.sound.


Enums can have constructors. The enum actually works like a superclass for all of the enum options (CAT, DOG, FISH) in your example.

You can define a constructor both for the superclass (Animals) and for the individual enum options (CAT, DOG, FISH). The enum option constructor(s) can either overload or override the superclass constructor(s).


Just to let you know I encountered quite a few questions on enums on the SCJP exam when I sat it last week. I don't normally use them and hadn't really revised them so don't think I did that well on those particular questions - although I still passed the exam :)

I know every exam picks your questions from a random set, but for some reason questions on enums seem to be a favourite of the exam authors...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜