Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Usage of Enum...

 
Abhijit Kolhatkar
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi All,
There is a post by our fellow rancher Ade Barkah, in some of JavaRanch Forum.
I read that and was amazed and confused by his/her findings....
Thanks for that...

I will quote that example:
We can declare an ENUM as a member variable of a class , as follows:

class TestClass
{
enum myEnum
{
RED,
WhatIsThis
{
void AMethodInEnum()
{}
}
}
/** rest of the class defination follows */
...
...
}//end of class
I have a coupl of questions:
1. How can we use this Enum???
2. the method declared inside the enum, doesnt lead to any compile/run time error.. How can we call this method??
3. To what does this method belongs? For sure, it doesnt belong to the class. Does it belong to the enum then?
4. If the method belongs to enum, is it not violating one of the principles of OOPS, implemented in JAVA. I.e. a method can not exists without a class??

Thanks
Abhijit
 
Burkhard Hassel
Ranch Hand
Posts: 1274
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi, cowboys!

Abhijit Kolhatkar asked:
1. How can we use this Enum???

I don't refer to the original example since it is somewhat incomplete.

So I made another example:


Cat, Fish and dog are the constants of the enum.
The method is associated with all constants of the enum. It will be the same for all of them unless the method is not overridden for individual constants of the enum.



2. the method declared inside the enum, doesnt lead to any compile/run time error.. How can we call this method??

The method in the original example cannot be called (exception: via reflection).
There should be a method for ALL constants, overriden maybe in certain constants.
It is called like in the animal example.

3. To what does this method belongs? For sure, it doesnt belong to the class. Does it belong to the enum then?

Yes, belongs to the enum.



4. If the method belongs to enum, is it not violating one of the principles of OOPS, implemented in JAVA. I.e. a method can not exists without a class??

No, an enum is a special form of a class. An enum extends class java.lang.Enum<E>.




When you'd like to have your original example return something usefull, you should insert a method for all the constants, as in the following:









Yours,
Bu.
 
Abhijit Kolhatkar
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks a Ton Bu...
All my questions were answered and infact the explanations were pretty helpful too...

Thanks Once again....

Abhijit
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic