Solved

enum in constructor

Posted on 2014-01-10
7
401 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
Enabling OSINT in Activity Based Intelligence

Activity based intelligence (ABI) requires access to all available sources of data. Recorded Future allows analysts to observe structured data on the open, deep, and dark web.

 
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

Threat Intelligence Starter Resources

Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

Join & Write a Comment

For beginner Java programmers or at least those new to the Eclipse IDE, the following tutorial will show some (four) ways in which you can import your Java projects to your Eclipse workbench. Introduction While learning Java can be done with…
Basic understanding on "OO- Object Orientation" is needed for designing a logical solution to solve a problem. Basic OOAD is a prerequisite for a coder to ensure that they follow the basic design of OO. This would help developers to understand the b…
Viewers learn about the “while” loop and how to utilize it correctly in Java. Additionally, viewers begin exploring how to include conditional statements within a while loop and avoid an endless loop. Define While Loop: Basic Example: Explanatio…
The viewer will learn how to implement Singleton Design Pattern in Java.

758 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

Need Help in Real-Time?

Connect with top rated Experts

22 Experts available now in Live!

Get 1:1 Help Now