Solved

enum in constructor

Posted on 2014-01-10
7
407 Views
Last Modified: 2014-01-29
Hi,
I am trying below example

http://www.avajava.com/tutorials/lessons/how-do-i-use-the-enum-type-with-a-constructor.html ee


I see in this example code like below

 
public enum Food {
    HAMBURGER(7), FRIES(2), HOTDOG(3), ARTICHOKE(4);

    Food(int price) {
      this.price = price;
    }

    private final int price;

    public int getPrice() {
      return price;
    }
  }


Is above code represents Food constructor or enum constructor. I am not clear on that. what is the purpose of enum inside private constructor.
please advise
Any links resources ideas highly appreciated. Thanks in advance
0
Comment
Question by:gudii9
  • 3
  • 2
  • 2
7 Comments
 
LVL 19

Accepted Solution

by:
Ken Butters earned 300 total points
ID: 39772550
The enum is defining which types of food there are...

HAMBURGER
FRIES
HOTDOG
ARTICHOKE

in addition to a type of food, each of the enum values is also setting a price for each enum.

HAMBURGER(7) ~ price of hamburger = 7
FRIES(2) ~ price of fries = 2
HOTDOG(3) ~ price of Hotdog = 3
ARTICHOKE(4) ~ price of artichoke = 4

Here is link to java page that gives tutorial on enums that uses a similar example with planets:

http://docs.oracle.com/javase/tutorial/java/javaOO/enum.html
0
 
LVL 26

Expert Comment

by:dpearson
ID: 39773900
Is above code represents Food constructor or enum constructor.

It's actually both.

Food(int price) { ... }

Is the constructor for Food, which is itself an enum.  So it's also an enum constructor.

Usually enums are just a simple list of values: A,B,C.
This is showing how you can attach more values to an enum - in this case "price".

Doug
0
 
LVL 7

Author Comment

by:gudii9
ID: 39816098
I was reading more on constructor here
http://www.javaworld.com/article/2076204/core-java/understanding-constructors.html

It's actually both.

Food(int price) { ... }


I still not clear how it is constructor to the class since class name is EnumDemo right?
Does enum always need a constructor to use it. please advise
0
Master Your Team's Linux and Cloud Stack

Come see why top tech companies like Mailchimp and Media Temple use Linux Academy to build their employee training programs.

 
LVL 26

Expert Comment

by:dpearson
ID: 39816305
Let's start with a simpler example:

public class EnumDemo {
       // This is the constructor for EnumDemo
       public EnumDemo() {
       }

	public enum Food {
		HAMBURGER, FRIES, HOTDOG, ARTICHOKE;
	}
}

Open in new window


This is a single class (EnumDemo) that has a constructor and also contains an enum.

So far I assume there's no confusion.

Then we can change this into a more complex enum like this:

public class EnumDemo {
       // This is the constructor for EnumDemo
       public EnumDemo() {
       }

	public enum Food {
                HAMBURGER(7), FRIES(2), HOTDOG(3), ARTICHOKE(4) ;

                // This is a constructor for the Food enum
                // NOT the enumDemo class.
		Food(int price) {
			this.price = price;
		}

		private final int price;

                // This is a method on the Food enum
                // NOT the enumDemo class
		public int getPrice() {
			return price;
		}
        }
}

Open in new window


The constructor we added was a constructor for the Food enum.  Not for the EnumDemo class (which still has a constructor - the one we created at the start).

Does that make sense?

Doug
0
 
LVL 7

Author Comment

by:gudii9
ID: 39818781
sounds good.

for (Food f : Food.values()) {
                  System.out.print("Food: " + f + ", ");

                  if (f.getPrice() >= 4) {
                        System.out.print("Expensive, ");

where is values() method on the  Food enum defined. I do not see that.

public enum Food {
            HAMBURGER(7), FRIES(2), HOTDOG(3), ARTICHOKE(4);

How jave know the value within parenthesis like 7 in HAMBURGER(7) is referred as price.
What is the use of enum here instead of a class as we have variables and methods as well in this enum.
Please advise
0
 
LVL 19

Expert Comment

by:Ken Butters
ID: 39818862
A java enum is not necessarily a simple class that lists possible values in the manner that you may have become accustomed to in other languages.

It can be defined that way , but in Java, it does not have to be.

The way java knows that hamburger(7) refers to a price is because of the contructor use for each enum value.... each 'Food'.

This says that for each of the enums...
HAMBURGER(7), FRIES(2), HOTDOG(3), ARTICHOKE(4) ;

... keeping in mind that each of the above is one of the enumerations of a type of FOOD.

That the food will be defined with a constructor for the food...

Food(int price) {
                  this.price = price;
            }

So when you list "HAMBURGER(7)"

then this in turn invokes

Food(int price) {
                  this.price = price;
            }

Where price is 7.


now you have a HAMBURGER enum
            with a value of 7 stored in the "price" variable of Hamburger.

There is a separate "price" field ... one for EACH enumeration of HAMBURGER(7), FRIES(2), HOTDOG(3), ARTICHOKE(4) ;
0
 
LVL 26

Assisted Solution

by:dpearson
dpearson earned 200 total points
ID: 39818992
where is values() method on the  Food enum defined. I do not see that.

Yeah that's good spotting.  The values() method is actually something you get for free on any enum.  You don't have to write it yourself.  A bit like how you get "toString()" on any object.

I think Ken explained how the "7" is tied into being the price.

You can compare the price example with this other piece of code, where we're instead storing the number of calories in the enum:

public class EnumDemo {
       // This is the constructor for EnumDemo
       public EnumDemo() {
       }

	public enum Food {
                HAMBURGER(700), FRIES(800), HOTDOG(450), ARTICHOKE(100) ;

                // This is a constructor for the Food enum
                // NOT the enumDemo class.
		Food(int calories) {
			this.calories = calories;
		}

		private final int calories;

                // This is a method on the Food enum
                // NOT the enumDemo class
		public int getCalories() {
			return calories;
		}
        }
}

Open in new window


Hope this is all getting clearer,

Doug
0

Featured Post

Master Your Team's Linux and Cloud Stack

Come see why top tech companies like Mailchimp and Media Temple use Linux Academy to build their employee training programs.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
eclipse package explorer vs project explorer view 2 121
eclipse argument 14 60
ForLoop Example 3 48
hibernate insert example 13 28
By the end of 1980s, object oriented programming using languages like C++, Simula69 and ObjectPascal gained momentum. It looked like programmers finally found the perfect language. C++ successfully combined the object oriented principles of Simula w…
Introduction This article is the second of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers the basic installation and configuration of the test automation tools used by…
Video by: Michael
Viewers learn about how to reduce the potential repetitiveness of coding in main by developing methods to perform specific tasks for their program. Additionally, objects are introduced for the purpose of learning how to call methods in Java. Define …
This tutorial covers a step-by-step guide to install VisualVM launcher in eclipse.

806 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question