new.programmer new.programmer - 6 months ago 23
Java Question

i have confusion in concept of classes and objects in Java

i have confusion in concept of classes and objects in Java
i did the following code but i'm not sure if it right!!!
So How can i test it and invoking this class in the main class?

import java.util.*;
public class Pizza {
public String pizzasize;
public int cheese;
public int pepperoni;
public Pizza (String pizzasize1,int cheese1,int pepperoni1){
pizzasize= pizzasize1;
cheese=cheese1;
pepperoni=pepperoni1;
}


this method chick pizza size then declaring and assign pizza cost

public void setPizza(String pizzasize1){
switch(pizzasize1)
{
case "S":
case "s":
{
int pc=10;break;
}
case "M":
case "m":
{
int pc=12;break;
}
case "L":
case "l":
{
int pc=14;break;
}
default:System.out.print("Wrong");
}//switch
pizzasize= pizzasize1;
}


..

public void setPizza(int cheese1,int pepperoni1){
cheese=cheese1;
pepperoni=pepperoni1;
}

public String getPizza(){
return pizzasize;
}
public int getPizza1(){
return cheese;
}
public int getPizza2(){
return pepperoni;
}

public void calcCost (int pc){
double totalCost = pc+(cheese+pepperoni) *2;
}


finally this method for sample output

public void getDiscriptions(String pizzasize,int cheese,int pepperoni,double totalCost){
Scanner sc=new Scanner(System.in);
System.out.println("place order");
System.out.println("size: L,M,s");
pizzasize=sc.next();
System.out.println("cheese: ");
cheese=sc.nextInt();
System.out.println("pepperoni: ");
pepperoni=sc.nextInt();
System.out.println("");
System.out.println("your order placed is/nlarge pizza with"+cheese+"cheese,"
+pepperoni+"pepperoni,/ntotal cost is"+totalCost);
}

}//

Answer

Not bad, but a few pointers:

switch statements don't work with Strings, they work with byte, short, char, and int primitive data types. They also work with enumerated types.

You could set up an enum with the sizes:

public enum Size {S,M,L};

Then your size field would be of type Size:

private Size pizzaSize;

Make your fields all private instead of public. That means they cannot be seen from outside the Pizza class. They can be read using getter methods. If they need to be changed, you can provide setter methods too.

Example:

public class Pizza {

  //cannot be accessed directly from other classes
  private int cheese;

  //allows other classes to read the value, but not change it
  public int getCheese() {
    return cheese;
  }

  //provide a setter like this if you want other classes to be able to change the value.
  public void setCheese(int cheese) {
    this.cheese = cheese;
  }

}

I have omitted the other fields for clarity. Note also that the getter and setter methods match the field name, except with get and set prepended, and the first letter of the field capitalized. The compiler does not require this, but it is accepted convention and good practice.