BitNinja
BitNinja

Reputation: 1487

Only direct subclasses must implement method

Let's say I'm programming a zoo simulator (my favorite example when dealing with inheritance). I've got a general Animal class. Then I have two classes that extend Animal called Bird and another one called LandAnimal. All subclasses of Bird will move in the same way (I'm not planning on having any ostriches in my zoo!), and likewise with LandAnimal. Therefore, I made a move() method in the Animal class. But birds and land animals move so differently that I didn't want to add anything to the method. So I marked it abstract overlooking the fact that all subclasses of Bird are going to have to implement it. This didn't seem good to me, even if the code was just

@Override
public void move()
{
    super.move();
}

It still doesn't feel right to have that in every file.

The main question is: Is there any way for me to make only direct subclass implement a method (Bird has to but the Sparrow extends Bird class doesn't)?

Edit: I have overlooked something relating to my simulator. I would rather not have 3 different lists to iterate over and call move() on them. I would like to have one ArrayList<Animal> that I can use for updating and drawing.

Upvotes: 0

Views: 826

Answers (3)

jackarms
jackarms

Reputation: 1333

Yes -- for abstract methods (and interface methods, which are the same thing), each class must implement all of them, but super classes that implement them count as valid. So if Bird implements the abstract move method, Sparrow doesn't have to because its parent class already implemented it.

Upvotes: 0

khelwood
khelwood

Reputation: 59111

If Bird implements the method and Sparrow extends Bird, then Sparrow has an implementation; it doesn't need to provide another one.

Upvotes: 0

&#211;scar L&#243;pez
&#211;scar L&#243;pez

Reputation: 236034

If you implement the move() method in Bird and Sparrow doesn't have to change it, then you don't have to implement it in Sparrow, it'll be inherited as-is without the need to re-implement it to only call super.move();. That's the whole idea of inheritance: in the subclasses you reuse the code from the superclasses and only add or override methods in those cases when the behaviour is different from the parent's.

Upvotes: 5

Related Questions