user3571396
user3571396

Reputation: 123

restricting a class method overridden by few child classes

I have a 1 Question asked in 1 Interview

class Birds {
     public void fly();
     public void eat();
     public void sleep();
}

Have several other classes extending it like -

Sparrow extends Birds{
   overriding fly();// Sparrow can have its own style to fly
   overriding eat();
   overriding sleep();
}

Eagle extends Birds{
   overriding fly();// Eagle can have its own style to fly

}

Ostrich extends Birds {
    overriding fly();// Ostrich could not fly !!!
}

How can I restrict such situation ?? Since parent class doesn't aware of its Child class here. Birds class is extended by several classes some could override Some could not be able to override.

Upvotes: 1

Views: 91

Answers (2)

Alexander Ivanov
Alexander Ivanov

Reputation: 2143

You can simply add FlyingBird and GroundBird classes and make them abstract.

public class Birds {
    public void eat() {
        // default implementation
    }
    public void sleep() {
        // default implementation
    }
}

abstract class FlyingBird extends Birds {
    public abstract void fly();
}

abstract class GroundBird extends Birds {
    public abstract void walk();
}

class Sparrow extends FlyingBird {
    @Override
    public void eat() {
        // different implementation
    }
    @Override
    public void sleep() {
        // different implementation
    }
    @Override
    public void fly() {
        // some impl
    }
}

class Eagle extends FlyingBird {
    @Override
    public void fly() {
        // some impl
    }
}

class Ostrich extends GroundBird {
    @Override
    public void walk() {
        // walk implementation
    }
}

Upvotes: 0

Bathsheba
Bathsheba

Reputation: 234665

You need to use composition:

  1. Define an interface called, say, Flyable which has a fly() method. Sparrow and Eagle implement that interface. Ostrich does not.

  2. Define an interface called Living, say which has eat() and sleep() methods. All your types implement that interface.

  3. You could point out to your interviewer that you could then have an Aeroplane() object that implements Flyable but not Living.

Upvotes: 3

Related Questions