Animal, Dog and Eye
HardClasses15 min
Write three classes: Eye, Animal and Dog. A dog is an animal (inheritance). An animal has eyes (composition).
new Eye(color): an eye with the fieldcolor(a string). Its methodblink()returns'blink'.new Animal(name, eyeColor): fieldsnameandeyes.eyesis an array of two newEyeobjects with the coloreyeColor. Every animal gets its own array and its own twoEyeobjects, and the two eyes are two different objects. The animal creates the eyes once, in the constructor, and keeps them: every read ofeyesgives the same array with the same twoEyeobjects.speak()ofAnimalreturns'<name> makes a sound', for example'Cat makes a sound'.describe()ofAnimalreturns'<name> has 2 <color> eyes', where<color>is the color of the eyes, for example'Cat has 2 green eyes'.Dogis a subclass ofAnimal:new Dog(name, eyeColor, breed)also has the fieldbreed.Dogoverridesspeak()with its own method that returns'<name> barks'.- Do not write
describe()inDog: it comes fromAnimal. - An eye is not an animal:
Eyedoes not extendAnimal, andAnimaldoes not extendEye. Check it with instanceof:dog instanceof Animalistrue, anddog instanceof Eyeisfalse.
Examples
new Dog('Rex', 'brown', 'Beagle').speak()Returns 'Rex barks'
new Dog('Rex', 'brown', 'Beagle').describe()Returns 'Rex has 2 brown eyes'
new Animal('Cat', 'green').eyes.lengthReturns 2
Asked at Reltio · Source
Loading the editor...
- An Eye keeps its color and blinks
- An Animal has a name, two eyes, speak() and describe()
- A Dog is an Animal with a breed and barks
Hidden tests run on Submit