Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

please explain the code and please anyone give example of overloading in enum

 
kapilg gupta
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
enum Animals {

DOG("Woof"),CAT("meow"),FISH("burble");
String sound;
Animals(String s)
{
sound=s;
}
}
class TestEnum {
static Animals a;
public static void main(String args[])
{
System.out.println(a.DOG.sound +" "+a.FISH.sound);
}
}
output:-woof burble
i want to ask when values are assigned in sound also how oveloading can be done in enum
 
Naseem Khan
Ranch Hand
Posts: 809
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


Above enum code is similar to following code:




Here DOG, CAT, FISH all become named constant of type Animal.

These three named constants DOG, CAT, FISH refer to the three Animals instances and these instances are created when Animals class is initialized after it is loaded.

When you call a.DOG, this will return a instance of Animal.

Each instance has a instance variable sound...


1. a.DOG.sound returns woof

2. a.FISH.sound returns burble

Second part of your question


Originally posted by kapilg gupta:
i want to ask when values are assigned in sound also how oveloading can be done in enum



Since enum is a normal java class, so you can overload constructors/methods in enum just like old java class. Same rule of overloading will also apply here.


regards


Naseem
[ June 16, 2006: Message edited by: Naseem Khan ]
 
Naseem Khan
Ranch Hand
Posts: 809
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Following code overloads constructor as well as method.

overloading.





Regards


Naseem
[ June 16, 2006: Message edited by: Naseem Khan ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic