SOLID Principles: Liskov Substitution Principle

public class Bird {

public void eat() {
System.out.println("I can eat.");
}

public void fly() {
System.out.println("I can fly.");
}
}
public class Swan extends Bird {

@Override
public void eat() {
System.out.println("OMG! I can eat pizza!");
}

@Override
public void fly() {
System.out.println("I believe I can fly!");
}
}
public class Main { 

public static void letBirdsFly(List<Bird> birds) {
for(Bird bird: birds) {
bird.fly();
}
}

public static void main(String[] args) {
List<Bird> birds = new ArrayList<Bird>();
birds.add(new Bird());
letBirdsFly(birds);
}
}
public static void main(String[] args) {
List<Bird> birds = new ArrayList<Bird>();
birds.add(new Swan());
letBirdsFly(birds);
}
I believe I can fly!
public class Penguin extends Bird {    @Override
public void eat() {
System.out.println("Can I eat taco?");
}
@Override
public void fly() {
throw new UnsupportedOperationException("Help! I cannot fly!");
}
}
public static void main(String[] args) { 
List<Bird> birds = new ArrayList<Bird>();
birds.add(new Swan());
birds.add(new Penguin());
letBirdsFly(birds);
}
I believe I can fly! Exception in thread "main" java.lang.UnsupportedOperationException: Help! I cannot fly!
public static void letBirdsFly(List<Bird> birds) { 
for(Bird bird: birds) {
if(!(bird instanceof Penguin)) {
bird.fly();
}
}
}
public class Bird {     public void eat() { 
System.out.println("I can eat.");
}
}
public class FlyingBird extends Bird { public void fly() {
System.out.println("I can fly.");
}
}
public class Swan extends FlyingBird { @Override
public void eat() {
System.out.println("OMG! I can eat pizza!");
}
@Override
public void fly() {
System.out.println("I believe I can fly!");
}
}
public class Penguin extends Bird { @Override
void eat() {
System.out.println("Can I eat taco?");
}
}
public class Main {    public static void letBirdsFly(List<FlyingBird> flyingBirds) {
for(FlyingBird flyingBird: flyingBirds) {
flyingBird.fly();
}
}
public static void main(String[] args) {
List<FlyingBird> flyingBirds = new ArrayList<FlyingBird>();
flyingBirds.add(new Swan());
letBirdsFly(flyingBirds);
}
}
I believe I can fly!

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store