Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 336
MrDetail Avatar asked Dec 01 '22 05:12

MrDetail


2 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

like image 98
RNJ Avatar answered Dec 04 '22 09:12

RNJ


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.

like image 34
Matt Whipple Avatar answered Dec 04 '22 09:12

Matt Whipple