Monday, August 26, 2019

Liskov Substitution Principle Example

Liskov Substitution Principle. As per LSP, functions that use references to the base classes must be able to use objects of derived class without knowing it.

public interface MyInterface {
 public int getSpeed();
 public int getCubicCapacity();
}
Implementation of MyInterface
public class MyInterfaceImplFirst implements MyInterface  {
 public int getSpeed()
 {
  int speed = 100;
  return speed;
 }
 public int getCubicCapacity() {
  return 200;
 }
}
Implementation of MyInterface
public class MyInterfaceImplSecond implements MyInterface {

 public int getSpeed()
 {
  int speed = 40;
  return speed;
 }
 public int getCubicCapacity() {
  return 150;
 } 
}

public class LspMainTest {
 public static void main(String[] args) {
  MyInterface myInterface = new MyInterfaceImplFirst();
  myInterface.getSpeed();
  myInterface.getCubicCapacity();

  MyInterface myInterface1 = new MyInterfaceImplSecond();
  myInterface.getSpeed();
  myInterface.getCubicCapacity();
 }
}
As you can see in this example we can use references to the base classes and by useing objects of derived class we can access all the methods of base class.

No comments:

Post a Comment