Can an extended class not inherit a method?

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?

Answers


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


Need Your Help

Creating a contact form which displays error when not filled in? (validation)

php javascript html css contact-form

I asked this question before about trying to create a contact form which allows validation (displays an error when not filled in or filled in incorrectly) - Creating a contact form which displays e...