Java

OOP GUIDE / WORK

 

FOOD SUPERCLASS

 

Topics

  • Inheriting from the Object class
  • Polymorphic references
  • Overriding methods

 

TASK – PART 1 – CREATING THE FOOD CLASS

 

Create the Food class with the following specification:

 

  • It has the following instance variables:
    • private String name – The name of the food (ex: Cake)
    • private int amount – The amount of food (ex: 2)
    • private String units – The units associated with amount (ex: slices)
    • private String flavour – The flavour of the food

 

  • It has a constructor that simply gets a value for all of the instance variables.

 

  • It has an instance method named howMuch() that returns a String containing amount followed by the units.  For example, it might return 4 liters or it might returns 250 grams.

 

TASK – PART 2 – TESTING FOOD

 

A – BASIC TESTING

 

1-Inside a FoodTester class, add a main function. 

 

2-Then, create a Food object name food.  You decide what values the instance variables should get.

 

3-Call the howMuch() method on your Food object to make sure it works.  Output its result to screen.

 

B – INHERITANCE FROM THE OBJECT CLASS

 

1-Because Food doesn’t specifically extend another class, it actually extends the Object class.  This means it inherits all of the functionality in the Object class.  This is where it gets its toString() method. 

 

Output the food object to screen to call the toString() method in Object.  More about this later.

 

2-Because it inherits from Object, we can do the following polymorphic reference:

 

          Object obj = new Food(…);

 

Do the above for a new Food object of your choice.

 

3-Try calling the method howMuch() on obj.  What happens?  Comment this out after.

 

4-To get the full functionality from obj, we can cast it to a Food object.  We do this by doing:

 

          Food f = (Food)obj;

 

Do the above.

5-Now try calling the howMuch() method on f.  It should work.


Summary: When we have an Object reference, we can only use functionality that is in the Object class even if the reference is really to a Food object (or any other object).

C – OVERRIDING METHODS

 

1-Add a toString() to the Food class.  Make it simply return “Food is yummy”.

 

2-Back in the main function, call the Food’s toString() method of f. 

3-Now, call the toString method on obj.  Notice that the result is actually the toString method from Food!

 

Summary: So we can only use Object functionality on Object references, but if we override any of that functionality in a subclass, Java will actually call that overriding method automatically.

 

D – A USE FOR POLYMORPHISM

 

1-In the FoodTester class, under the main function, add the following function header:

 

public static void outputStuff(Object o)

{

   System.out.println(o);

}

 

2-Back in main, at the bottom, call the function passing the Food object f to it.

 

Summary:  We are able to create a function that can receive any Object.