Skip to main content
2 of 3
added 269 characters in body
Flater
  • 5.7k
  • 19
  • 23

This is not a bad overall attempt, but there are some issues you should pick up further. I'm going to avoid giving you the straight answer where possible, as the true value is found in finding the answers yourself:

  • Not every cat has 4 legs. Not every bug has 6 legs. If my cat only has 3 legs, how could this code facilitate my cat, who should be walking on 3 legs? It seems safest to not hardcode this number. Same thing applies to the color of the animals.
    • Interestingly, you've already fixed it for the number of wings a bird has. The same solution applies for legs and color too.
  • Rather than have each subtype set all of its fields, you should consider making the setting of the Animal fields reusable. Instead of each subtype doing the same thing, how about you delegate this job down to the Animal constructor itself.
  • The bird's move method correctly allows for the "flying" message to be given instead. However, when you don't want to return the "flying" message, you've hardcoded the same response that your Animal class already implemented. Instead of hardcoding this message a second time, try to find out if there is a way that the Bird.move method is able to just reuse the base Animal.move output (when the bird does not have sufficient wings).
    • This solution entails having a proper override, so make sure that Bird.move overrides Animal.move before you tackle this.
  • After all these things are tackled, reconsider the access modifiers you use on leg_number, color and wing_number.
    • It should be private when you want no one other than the class itself to make use of it. You should use this as the default option. Only use the other access modifiers when you have a genuine need for them. Try to start by keeping everything private, and whenever you feel like something shouldn't be private, consider if you need to open this up to others or not.
    • It should only be protected if subtypes should be able to make use of it, but not other external code.
    • It should only be public when external code should be able to make use of it.

Note that if you want to test if your inheritance was properly implemented, you should try to work with your objects by using the base class:

Animal myCat   = new Cat();    
Animal myBug   = new Bug();
Animal myBird1 = new Bird(2);
Animal myBird2 = new Bird(0);

If you did everything right, your code should behave the same way (and compile, for starters) when you change all these variable types to Animal. If your code does not behave the same way, then you've not properly implemented your inheritance.

Flater
  • 5.7k
  • 19
  • 23