My question is: can I create a class that extends another class, but choose not to inherit a particular method?
A simple example, I have an abstract Bird class with one method, fly(). I want to create classes for different species of birds, but penguins can't fly. How can I ensure that a penguin object can not call the fly() method?
No you cant
The closest you can get is to override the method and throw
@Override
public void fly() {
throw new UnsuportedOperationException();
}
The Java API does this sometimes but I see this as bad design personally.
What you could do is have a hierarchy of Bird and two sub-classes FlyableBird and NonFlyableBird and then have Penguin hang off NonFlyableBird. The fly method would then only be in FlyableBird class. The bird class could still contain things like makeNoise() (all birds make noises dont they?) which are common to both FlyableBird and NonFlyableBird
No you can't, that would break polymorphism fundamentally. You have to implement the function and do something like throw an Exception or do nothing.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With