Details of Liskov Substitution Principle Example

Liskov Substitution Principle (LSP)

public class Bird
{
void fly()
{
// Fly function for bird
}
}

public class Parrot extends Bird
{
@Override
void fly()
{

}
}

public class Ostrich extends Bird
{
// can't implement fly since Ostrich doesn't fly
}
  1. If a subclass returns an object that is completely different from what the superclass returns.
  2. If a subclass throws an exception that is not defined in the superclass.
  3. There are any side effects in subclass methods that were not part of the superclass definition.

How do programmers break this principle?

Liskov Substitution Principle Example

public abstract class BankAccount
{
public boolean withDraw(double amount);

public void deposit(double amount);

}
public class BasicAccount extends BankAccount
{
private double balance;

@Override
public boolean withDraw(double amount)
{
if(balance > 0)
{
balance -= amount;
if(balance < 0)
{
return false;
}
else
{
return true;
}
}
else
{
return false;
}
}

@Override
public void deposit(double amount)
{
balance += amount;
}
}
public class PremiumAccount extends BankAccount
{
private double balance;
private double rewardPoints;

@Override
public boolean withDraw(double amount)
{
if(balance > 0)
{
balance -= amount;
if(balance < 0)
{
return false;
}
else
{
return true;
updateRewardsPoints();
}
}
else
{
return false;
}
}

@Override
public void deposit(double amount)
{
this.balance += amount;
updateRewardsPoints();
}

public void updateRewardsPoints()
{
this.rewardsPoints++;
}
}
public class InvestmentAccount extends BankAccount
{
private double balance;

@Override
public boolean withDraw(double amount)
{
throw new Expcetion("Not supported");
}

@Override
public void deposit(double amount)
{
this.balance += amount;
}

}

How to avoid violating LSP in the design?

  • Use Interface instead of Program.
  • Composition over inheritance
public interface IBankAccount
{
boolean withDraw(double amount) throws InvalidTransactionException;
void deposit(double amount) throws InvalidTransactionException;
}

Conclusion

--

--

--

Software Developer, Writer

Love podcasts or audiobooks? Learn on the go with our new app.

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
Yogesh Mali

Yogesh Mali

Software Developer, Writer

More from Medium

Spring boot cron job example every 5 minutes

How to Develop a Tweet Scheduler using SpringBoot and MongoDB

All new Java 8 — time API — LocalDate

Getting started with SpringBoot