• 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
  • Ron McLeod
  • Rob Spoor
  • Tim Cooke
  • Junilu Lacar
Sheriffs:
  • Henry Wong
  • Liutauras Vilda
  • Jeanne Boyarsky
Saloon Keepers:
  • Jesse Silverman
  • Tim Holloway
  • Stephan van Hulst
  • Tim Moores
  • Carey Brown
Bartenders:
  • Al Hobbs
  • Mikalai Zaikin
  • Piet Souris

Is it correct to consider Java enum fields has objects?

 
Ranch Hand
Posts: 56
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
If you have an enum like Book which for example, has the constant PAPERBACK, is it correct to consider the PAPERBACK its own datatype? As if it is an object field? I am puzzled because I don't really understand how we can call constructors on them, for example, when I look at this code, it seems like PAPERBACK and HARDBACk are types and each instantiated with one int instance variable set to the value. Am I right in thinking this?
 
Sheriff
Posts: 26777
82
Eclipse IDE Firefox Browser MySQL Database
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
No, PAPERBACK and HARDBACK are instances of type Book. And where you see PAPERBACK(100), that's the constructor for the PAPERBACK instance. Sure, it looks different from a regular constructor but that's how you do it for an enum.

And if PAPERBACK was a data type? Then you should be able to use it as the type of a variable, or as the type returned by a method, or in several other places where I won't carry on because by now you can see that doesn't work. Try it and see what the compiler says.
 
Saloon Keeper
Posts: 24314
167
Android Eclipse IDE Tomcat Server Redhat Java Linux
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Java classes don't have "objects", they have properties. A Property can be an object reference or it can be a primitive.

Java enums are not like enums in most other languages. Most languages implement enums as a constrained list of named scalar values. Java, on the other hand, implements enums as something that is very class-like. So class-like that in fact, a Java enum can define its own properties. And methods. Although that's not something that should be abused.
 
Saloon Keeper
Posts: 1306
40
Eclipse IDE Postgres Database C++ Java
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
In addition to what Paul said, which is correct and valid and true...

If each enum value was its own type, it could have its own public methods and data members which were different than the ones that the other values for that enum have.

This is not the case, at least for data members.

Each enum value can have its own implementation for methods defined by the enum, and its own values for data members.

In fact, someone just asked a tricky question about how that works over on the OCJP forum this morning.

I was incorrectly describing this as "like a limited and fixed inheritance hierarchy" but you and Paul cured me just now of doing that (not joking).

Each enum value really just is an instance of the same type defined collectively (here, Book) because none of them can have any more or different methods or data members.

This was actually a really good question, or at least one that I benefited from, despite thinking I had "Enum use in Java all sowed up!"

My usage was correct, but I was still using inappropriate terminology to describe what I was doing.

What you can actually do if you engage in severe ENUM abuse is trickier than I had thought.
Note this is considered abuse, like a lambda, and ENUM should be short and cute.

So exploring if the different enum instances can have their own independent public methods, and we could call them from outside, the answer was no:
jshell> enum Seasons {
  ...>     WINTER { public String getHours() { return "Woof!";} },
  ...>     SUMMER { public String getHours() { return "Meow!";} public String getMinutes() { return "Tweet!";} };
  ...>             abstract public String getHours();}
|  replaced enum Seasons

jshell> Seasons.WINTER.getHours();
$5 ==> "Woof!"

jshell> Seasons.SUMMER.getHours();
$6 ==> "Meow!"

jshell> Seasons.SUMMER.getMinutes();
|  Error:
|  cannot find symbol
|    symbol:   method getMinutes()
|  Seasons.SUMMER.getMinutes();
|  ^-----------------------^


But what about internally?  It turns out that this works, but I would never do this in real code.  I consider it enum abuse:
jshell> enum Seasons {
  ...>     WINTER { public String getHours() { return "Woof!";} },
  ...>     SUMMER { public String getHours() { return "Meow!" +  getMinutes();} public String getMinutes() { return "Tw et!";} };
  ...>             abstract public String getHours();}
|  created enum Seasons

jshell> Seasons.SUMMER.getHours();
$8 ==> "Meow!Tweet!"


In the view to the world outside the enum, each value for the enum is the same type, that of the enum.
All values share the same data members and the same public methods being available, but can have their own values for those data members and their own implementations of each public method defined by the enum.

Come to think of it, the way that enums work (when you go beyond the trivial) is weird, it is not quite like the "fixed hierarchy of sub-types" that I had been describing it as, but nor would I say that all of the values are simply of the enum type (here, Book) because they can all provide their own implementations of any publicly defined methods on the enum.

The sections describing enum in the JLS are very complicated and make use of terms not used here.

I would say that trying to describe each constant value of an enum as either being a subtype or an instance of the common type is too simple, and conveys incorrect implications that a longer, fuller, more painful discussion would not.

If your enum contains no methods, it seems to work great to say the values are all just simply instances of the enum type.  There are a fixed number of them, and you can't create any more instances from outside.

But when methods are defined for the enum, trying to say tha tall the values are just simply instances of the common enum type doesn't work for me, object instances don't get their own overrides of instance methods in Java.  (They do in other languages, and I find it flat-out nuts!)

Your first priority is to figure out which things you can do with enums is on the exam.
Then how to do those things correctly, and spot incorrect usage attempts.
The lowest priority is how you want to describe this behavior in brief.
The full description is way beyond the scope of the exam, and can be seen in the JLS.
 
Jesse Silverman
Saloon Keeper
Posts: 1306
40
Eclipse IDE Postgres Database C++ Java
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Tim and I basically said the same thing here, which is quite common.

And he said it in way fewer words than I did, which is also common.

I'll fall back to a one sentence summary of my long post:
"For the exam, it is important to know what you can do with Java enums, how to do it, and how to spot incorrect attempts at doing it."

I can imagine various possible questions that they could ask about "What a Java enum or an enum value is like?" which would be a nightmare to write or answer.

Hopefully we won't face any of those questions.  Be ready for the ones about proper usage.
 
Antonio Moretti
Ranch Hand
Posts: 56
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Jesse Silverman wrote:Your first priority is to figure out which things you can do with enums is on the exam.
Then how to do those things correctly, and spot incorrect usage attempts.
The lowest priority is how you want to describe this behavior in brief.
The full description is way beyond the scope of the exam, and can be seen in the JLS.



While learning Java, I rely on analogies and a concepts that go deeper than Schildt. For example, in that old book "The Heads First Java", I was really able to grasp polymorphism because of the way it was explained with diagrams. I'd like to have that level of understanding of enums but HFJ doesn't explain it. From what I can gather from here, the enum Book in my example is like a class, and the fields it contains are like instances of that class. Is this correct? And only once instance of each allowed?
 
Marshal
Posts: 74042
332
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Antonio Moretti wrote:. . . the enum Book in my example is like a class, and the fields it contains are like instances of that class. . . .

Yes, but more so.
An enum IS‑A class and each of its constants (elements) IS‑AN instance of that class. The number of instances is always exactly the same as the number of elements declared, so your Book datatype will always have two instances in a particular JVM. Even if you pass one instance to a different JVM, e.g. via a socket, it will become the corresponding instance of that same enum, so each JVM will always have the same number of instances of each enum.
 
Jesse Silverman
Saloon Keeper
Posts: 1306
40
Eclipse IDE Postgres Database C++ Java
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I like what Campbell said, so will just say what I would add to that for the fuller picture.

Note that instances of a class (in Java) do not get the option of implementing their own versions of class methods.  There is just one definition that serves for all instances of the class. *

"Values" in enum's do have precisely this ability, as I think you can see in the examples given in the recent thread on the OCPJP forum.

You don't need to provide methods in your enum, and I had never done this before in my life before learning this relatively recently in Java and C# about the same time.

But if you do, or are working with code that is doing so, it is weird to think of the values as mere instances because each value can choose to override any methods that the enum defines.

Other than that, "What Campbell said!"

* - I realize this is no longer strictly true in the face of Modern Java, what with lambdas and method references and the ability to store one as a private instance member, but this would REALLY confuse the OP at this point...in a static sense it is still true, moreover, each and every instance presents the same API.
 
Campbell Ritchie
Marshal
Posts: 74042
332
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Jesse Silverman wrote:. . . instances of a class (in Java) do not get the option of implementing their own versions of class methods. . . . enum's do have precisely this ability . . .

Look in the Java™ Tutorials and the Java® Language Specification which have all sorts of examples about enums. An enum constant with its own methods is (I think) regarded as an instance of a subclass of the enclosing class.
 
Antonio Moretti
Ranch Hand
Posts: 56
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Jesse Silverman wrote:You don't need to provide methods in your enum, and I had never done this before in my life before learning this relatively recently in Java and C# about the same time.



What about getter methods? For example, in an of days of the week, we could the number of days to a private int field 'days'. We'd want this to be immutable, so private. So it would seem natural to me to provide a getter method to that otherwise the instance would need a public field.
 
Jesse Silverman
Saloon Keeper
Posts: 1306
40
Eclipse IDE Postgres Database C++ Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Yes.  This is a very common use case, and one of the simplest ones, for using the extended functionality of enum in Java compared to older languages to great effect!

I won't go into how we used to do such things in those days (including Java before enum arrived), it was MUCH messier both to maintain and to use!
 
Campbell Ritchie
Marshal
Posts: 74042
332
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Jesse Silverman wrote:. . . how we used to do such things in those days . . .

Effective Java by Joshua Bloch, 1st edition (2001) page 80.
 
reply
    Bookmark Topic Watch Topic
  • New Topic