• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

enum ???

 
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
why enum not gives an error at second SOP? and what a.b means i.e how to read it.

public enum E
{
a(1),b(2),c(3);

int i;
E(int i){this.i=i;}

public static void main(String [] str)
{
System.out.println(a); //1// output-->a
System.out.println(a.b); //2// output-->b not able to understand a.b ?
}
}

as in normal class

public class C
{
int i;
C(int i){this.i=i;}

public static void main(String [] str)
{
C a=new C(1);
C b=new C(2);
System.out.println(a.b); // compiler error
}

}




why enum not gives an error? and what a.b means i.e how to read it.
 
Ranch Hand
Posts: 84
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
a.b translates to E.b as enum elements are implemented as static fields.
 
Sheriff
Posts: 9708
43
Android Google Web Toolkit Hibernate IntelliJ IDE Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
An enum variable is like a static instance of the same enum. If you look at it like a class, this is how a class E (like your enum E) would look


Now if you see the code, a is an instance of the class E itself. So a.b refers to the static instance of class E declared at line# 4. Actually enums are converted to classes which extends the Enum class. Look on the internet for a good tutorial on enums...
reply
    Bookmark Topic Watch Topic
  • New Topic