Story points | 3 |
Tags | oop |
Hard Prerequisites |
|
This Challenge should test topics from your OOP knowledge
In this challenge you will create 3 classes
Animal
Dog
and Cat
class which both extends Animal
class (a dog is an animal and a cat is an animal)Dog
and Cat
class should only have 1 function, which is their own implementation of the sound()
function. This is polymorphismHome
class. But we’ll talk about that later…// Java
? dog = new Dog()
dog.eat() // -> 'Rax eats'
dog.sounds() // -> 'Dog barks'
? cat = new Cat()
cat.eat() // -> 'Stormy eats'
cat.sounds() // -> 'Cat meows'
// Javascript
var dog = new Dog();
dog.eat(); // -> 'Rax eat'
dog.sounds();// -> 'Dog barks'
var cat = new Cat();
cat.eat();// -> 'Stormy eats'
cat.sounds();// -> 'Cat meows'
Now let’s add composition. Make a new class called Home
. Lots of people have dogs and cats in their homes. Home
should have a function called adoptPet
that takes any Animal
as an input. The new pet should be stored in the Home
object in an array/list. The Home
object should also have a function called makeAllSounds
. It should work like this:
// Java
Home home = new Home()
? dog1 = new Dog()
? dog2 = new Dog()
? cat = new Cat()
home.makeAllSounds() // this doesn't do anything
home.adoptPet(dog1)
home.makeAllSounds()
// this prints:
// Dog barks
home.adoptPet(cat)
home.makeAllSounds()
// this prints:
// Dog barks
// Cat meows
home.adoptPet(dog2)
home.makeAllSounds()
// this prints:
// Dog barks
// Cat meows
// Dog barks
// Javascript
var home = new Home();
var dog1 = new Dog();
var dog2 = new Dog();
var cat = new Cat();
home.makeAllSounds();// this doesn't give/return any result/data
home.adoptPet(dog1);
home.makeAllSounds();
// this prints :
// Dog barks
home.adoptPet(cat);
home.makeAllSounds();
// this prints :
// Dog barks
// Cat meows
home.adoptPet(dog2);
home.makeAllSounds();
// this prints :
// Dog barks
// Cat meows
//Dog barks
This section is not compulsory. If you do this we’ll think you’re cool.
Add some functionality to adoptPet
so that an error/exception gets raised if you try to adoptThe same pet twice
eg:
home.adoptPet(dog1) // totally ok
home.adoptPet(dog1) // not ok at all