0

I'm in an AP Computer Science (high school level) and I'm still trying to grasp some things we're learning in class. We recently got an assignment to modify a 'Pizza' resource class. His directions from the worksheet were:

Part 1: Modify the old Pizza class written earlier. Add an equals() method which overrides the one in the Object class. Two Pizza objects are equal if the toppings, sizes and costs are the same. Use the PizzaMatch class to test the new method.

Part 2: Add a compareTo() method to implement the interface Comparable. This compareTo() should help you find the cheapest pizza in pizza.txt.**

And the output he wanted is

**Part 1 Output
Input a Pizza topping, size, and cost: 
sloppyJoe 15 15.30
That pizza is # 20 in the file.
ÏÏÏ
Input a Pizza topping, size, and cost: 
cheese 12 12.99
That pizza is not in the file.
Part 2 Output
The cheapest pizza: The 9 inch olive pizza will cost   $7.99** 

Here is Pizza (the resource class)

 import java.util.*; 
 import java.io.*;
 class Pizza 
{ 
  private int size; 
  private double cost; 
  private String topping; 
  public Pizza(int pizzaSize, double pizzaCost,String pizzaTopping) 
  { 
     size = pizzaSize; 
     cost = pizzaCost; 
     topping = pizzaTopping; 
  } 
  public void setSize(int input) 
  { 
     size = input; 
  } 
  public void setCost(double input) 
  { 
     cost = input; 
  } 
  public void setTopping(String input) 
  { 
     topping = input; 
  } 
  public int getSize() 
  { 
     return size; 
  } 
  public double getCost() 
  { 
     return cost; 
  } 
  public String getTopping() 
  { 
     return topping; 
  } 

  public String toString() 
  { 
     return (size + " inch " + topping + " pizza will cost $" + cost); 
  } 
}

And here is PizzaMatch

  import java.util.*;
  import java.io.*;

public class PizzaMatch   {
   public static void main (String [] args)throws Exception
   {

     Scanner keyboard = new Scanner(System.in);
     System.out.println("Input a Pizza topping, size, and cost: "); 
     String top = keyboard.next();  
     int size = keyboard.nextInt();
     double cost = keyboard.nextDouble();
     Pizza input = new Pizza(size, cost, top);
     int counter =1;
     boolean found = false;
     while(inFile.hasNext())
     {
        String t = inFile.next();  
        int s = inFile.nextInt();
        double c = inFile.nextDouble();
        Pizza temp = new Pizza(s,c,t);
       //System.out.println("Pizza #"+counter+"\t" + temp);
        if(temp.equals(input))
        {
           System.out.println ( "That pizza is # " + counter 
              + " in the file.");
           found = true;
        }
        counter++;         
     }
     if(!found)
        System.out.println("That pizza was not in the file.");

  }
}

Basically, I'm not sure where to start. I'm still a bit unsure of interfaces, as well. I realize that we have to make a .equals() method, but how? I started out writing

public Boolean equals(Pizza p)
{
 if(p==/*this is where I don't know what to write*/)
return true;
}

Any help would be greatly appreciated, for both Part 1 and Part 2 of the assignment! Thanks so much :)

Ellen Spertus
  • 6,576
  • 9
  • 50
  • 101
  • 3
    [Try to ask Short, Self Contained, Correct (Compilable) questions](http://www.sscce.org/) – Shreyos Adikari Apr 03 '14 at 21:18
  • 2
    *Two Pizza objects are equal if the toppings, sizes and costs are the same*. And equals() returns a boolean, not a Boolean. And it takes an Object as argument, not a Pizza. – JB Nizet Apr 03 '14 at 21:20
  • possible duplicate of [How do I override a method in a subclass?](http://stackoverflow.com/questions/5215612/how-do-i-override-a-method-in-a-subclass) – Jason C Apr 03 '14 at 21:26
  • Welcome to StackOverflow! I hope you don't mind constructive criticism: I recommend removing most of your source code. It's not relevant to your question. I changed "overwrite" to "override" in your title. – Ellen Spertus Apr 04 '14 at 18:19
  • Note that if you override equals(), you should override hashCode(). http://stackoverflow.com/questions/27581/overriding-equals-and-hashcode-in-java – Ellen Spertus Apr 04 '14 at 18:21

6 Answers6

4

If you want to override a method of a base class, in general the subclass method should have the same signature of the base.

If you look at the documentation for Object.equals(), you can see that it actually returns a boolean, not a Boolean. Also, it takes an Object parameter, not a Pizza parameter. So in your case, in Pizza, you'd need:

public boolean equals (Object o) {
    if (!(o instanceof Pizza))
        return false; // its null, or its not Pizza
    Pizza p = (Pizza)o;
    // compare relevant fields of 'this' with 'p' and return result.
    return ...;
}

Note, by the way, that Java has an @Override annotation that you should use to mark methods that are intended to override base methods:

@Override
public boolean equals (Object o) {
    if (!(o instanceof Pizza))
        return false; // its null, or its not Pizza
    Pizza p = (Pizza)o;
    // compare relevant fields of 'this' with 'p' and return result.
    return ...;
}

If you had used this annotation in your original example, the compiler would have generated an error stating that your equals() method didn't actually override the base.

As for the actual implementation, that's up to you. What does it take to make one Pizza equal another? You have the criteria listed in your requirements, so implementing equals will involve comparing those fields of this and p and determining if the two are equal or not.

The strategies for compareTo() are similar. Your Pizza will have to implement, e.g., Comparable<Pizza> and then override int compareTo(Pizza); the implementation should behave as defined in the documentation for Comparable.compareTo(), and the exact logic you use for determining the result depends on the requirements given in your problem description.

I recommend reading the official tutorial on Overriding Methods for Part 1, and the official tutorial on Object Ordering for Part 2. These are concise, well-written, and will give you the tools you need to solve these types of issues.

Jason C
  • 38,729
  • 14
  • 126
  • 182
2

To override a method, you need to declare it exactly the same as in the original. It's helpful to use the @Override annotation to enforce this.

In the case of equals(), you'd start with:

@Override
public boolean equals(Object o) {
  :
}

The skeleton is typically:

@Override
public boolean equals(Object o) {
  if (o instanceof Pizza) {
    // Do the comparison for Pizza objects.
  } else {
    // A Pizza object can only be equal to other Pizza objects.
    return false;
  }
}
Ellen Spertus
  • 6,576
  • 9
  • 50
  • 101
0

Well first of all you should add an @Override tag above the equals function because you're overriding Object's equals() function. Your professor told you to verify if the topping, size and cost were the same for both pizza's, this means that you should compare certain variables of both pizza's and not just try to compare one complete pizza with another as you're doing now (p==??).

tvervack
  • 81
  • 5
0

You'll want something like this:

@Override
public Boolean equals(Object o)
{
    //Make sure its a pizza
    if (o instanceof Pizza == false)
        return false;

    //Cast to a pizza
    Pizza p = (Pizza)o;

    //Compare the fields
    if(this.size == p.getSize() && this.cost == p.getCost() && this.topping == p.getTopping())
        return true;
    else
        return false;
}
Tyler
  • 17,669
  • 10
  • 51
  • 89
0

Its pretty simple, you override a method in a super class by defining the method with the same method signature in the derived class. In Object, the .equals method is defined as:

public boolean equals(Object obj)

So you make a method in your class with the same signature and provide your implementation. You didnt ask for the interface part, but ill include it anyway. An interface is a contract. It defines method signatures that an object must have if it implements the interface, but it does not provide an implementation. This will result in compile time errors if you havent provided the implementation in a method whose signature matches whats defined in the interface. Here you just want to add the keyword implements followed by the interface you wish to implement on the class declaration, then do pretty much exactly what you did with the equals method, only with compareTo.

See .equals here http://docs.oracle.com/javase/7/docs/api/java/lang/Object.html and compareTo here http://docs.oracle.com/javase/7/docs/api/java/lang/Comparable.html

Mark W
  • 2,791
  • 1
  • 21
  • 44
0

For the equals() you need something like this:

public boolean equals (Object o){
    boolean res=false;
    if (o instanceof Pizza){
        Pizza p0 = (Pizza) o;
        res=getTopping().equals(p0.getTopping())&&getSize().equals(p0.getSize())&&getCost().equals(p0.getCost());
    }
    return res;

}
rixhack
  • 1
  • 1