Reputation: 123
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
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
Reputation: 234665
You need to use composition:
Define an interface
called, say, Flyable
which has a fly()
method. Sparrow
and Eagle
implement that interface. Ostrich
does not.
Define an interface called Living
, say which has eat()
and sleep()
methods. All your types implement that interface.
You could point out to your interviewer that you could then have an Aeroplane()
object that implements Flyable
but not Living
.
Upvotes: 3