Object-Oriented Programming
Contents
Object-Oriented Programming#
Read Inheritance before you start with the exercises.
Abstract Animals#
Create a class Animal
encapsulating an animal. Members:
variable
legs
(number of legs provided to the constructor),variable
weight
(weight of the animal provided to the constructor,function
is_lightweight
(returnsTrue
if weight is below 10 kg,False
else),function
show_up
(show an ASCII art representation of the animal),function
say_something
(a virtual method).
The show_up
method has to take into account the legs
variable. Up to the number of legs we do not know anything about the animal’s appearance. Be creativ and print an abstract animal with the correct number of legs!
No idea? What about this 8-legged abstract animal:
(########):
//||||\\
Bonus: Everytime an Animal
object is created a message ‘An animal with … legs is hiding somewhere.’
Test your code by creating and showing animals with 0, 1,…, 8 legs.
Solution:
# your solution
Dogs#
Derive a class Dog
from the Animal
class (cf. exercise above). Implement a proper say_something
method (‘Wau’, for instance) and reimplement show_up
to show a dog instead of an abstract animal.
Note, that the constructor only takes the dog’s weight as argument. The constructor should call the base class’ constructor to set the correct number of legs (and show the bonus message, if implemented).
In your test code also check if the dog is lightweight.
Solution:
# your solution
Sitting Dog#
Add methods sit_down
and stand_up
to your Dog
class. Depending on which of both methods was called last, show_up
shall show a sitting or a standing dog.
Solution:
# your solution
Fish#
Derive a Fish
class from Animal
. Add a member function to_sticks
. After calling this function once, show_up
should show 10 fish sticks per kilogram of the fish instead of a live fish.
Don’t forget to implement say_something
(maybe ‘Blub’ or, more realistic, ‘’).
Solution:
# your solution