Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Understanding enum  RSS feed

 
miguel lisboa
Ranch Hand
Posts: 1281
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
(after i read this) i wrote this:


it looks like:

1) enum works like static, since i wasnt forced to create a new Person

2) enum is like an inner class, since it behaves like a class and lives inside another (yes, it can exist independently)

3) i infer that the only reason there is a constructor (private by design) is to get the param value

pls comment

TiA
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by miguel lisboa:

1) enum works like static, since i wasnt forced to create a new Person


I suppose that's right, the constants that make up an enum are implicitly static.


2) enum is like an inner class, since it behaves like a class and lives inside another (yes, it can exist independently)


Here, your enum is like a static inner class, yes. I'm actually not sure if code in the enum has access to the enclosing class's members -- I bet it does, although I've never thought about this before.


3) i infer that the only reason there is a constructor (private by design) is to get the param value



Well, isn't that the only reason for a constructor, ever, is to get some parameters and initialize the object? I believe you can have an enum constructor without parameters, as well.
 
miguel lisboa
Ranch Hand
Posts: 1281
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanks, Ernest

just look at what i found out:

C:\javas\Pessoa.java:7: non-static variable test cannot be referenced from a static context
CASA("111" + test),
^
1 error
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well, sure -- we've already established that an enum is like a static inner class. So make "test" a static member of Person, and it looks like this would work.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!