i'm trying to make a simple pizza assignment. i want to make it unable to make a pizza if the price is not 10, 20 or 30
public static void main(String[] args) {
Pizza tonno = new Pizza(3); //this should not be possible
Pizza tonno = new Pizza(10); //this should be possible
}
public class Pizza{
private int Price;
public Pizza(int price) {
Price = price;
}
public int getPrice() {
return Price;
}
public void setPrice(int price) {
Price = price;
}
}
if the given parameter is not 10, 20 or 30 the program should not make the new pizza. So if i make a new pizza and i give it the price 3 i don't want it to work. the price of the pizza should be 10, 20 or 30 nothing else.
how do i do this?
CodePudding user response:
This should work for you. This way anything outside the scope of Pizza is restricted to using the constructor that requires a 'PizzaType'.
Please note: I am assuming that the setPrice() method has some purpose, that is why I only used the enum in the constructor, and not just as a field of Pizza.
public class Pizza{
public enum PizzaType{
SMALL(10), MEDIUM(20), LARGE(30);
int price;
PizzaType(int price){
this.price = price;
}
}
private int Price;
private Pizza(int price) {
Price = price;
}
public Pizza(PizzaType p){
this(p.price);
}
public int getPrice() {
return Price;
}
public void setPrice(int price) {
Price = price;
}
}