[Last Call] Learn about multicloud storage options and how to improve your company's cloud strategy. Register Now

x
?
Solved

enum in constructor

Posted on 2014-01-10
7
Medium Priority
?
416 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 3
  • 2
  • 2
7 Comments
 
LVL 19

Accepted Solution

by:
Ken Butters earned 1200 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 28

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
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

 
LVL 28

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 28

Assisted Solution

by:dpearson
dpearson earned 800 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

How to Use the Help Bell

Need to boost the visibility of your question for solutions? Use the Experts Exchange Help Bell to confirm priority levels and contact subject-matter experts for question attention.  Check out this how-to article for more information.

Question has a verified solution.

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

Java had always been an easily readable and understandable language.  Some relatively recent changes in the language seem to be changing this pretty fast, and anyone that had not seen any Java code for the last 5 years will possibly have issues unde…
Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
This tutorial explains how to use the VisualVM tool for the Java platform application. This video goes into detail on the Threads, Sampler, and Profiler tabs.
Viewers will learn how to properly install Eclipse with the necessary JDK, and will take a look at an introductory Java program. Download Eclipse installation zip file: Extract files from zip file: Download and install JDK 8: Open Eclipse and …
Suggested Courses

650 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