Java OOP GUIDE / WORK FOOD SUPERCLASS Topics
TASK –
PART 1 – CREATING THE FOOD CLASS Create the
Food class with the following specification:
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.
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. 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. |
|