Skip to content

Instantly share code, notes, and snippets.

@krohit-bkk
Created January 20, 2024 17:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save krohit-bkk/93be21413dffb2021d3019601da56316 to your computer and use it in GitHub Desktop.
Save krohit-bkk/93be21413dffb2021d3019601da56316 to your computer and use it in GitHub Desktop.
Code snippet 2 for Loskov Substitution Principle
// Enforce fossil cars to have method to return mileage
interface Refuelables { float getMileage(); }
// Car has mileage
abstract class Car { abstract float calculateRange(); }
// Fossil car is a car
abstract class FossilCar extends Car { float fuel; abstract float getMileage(); }
// Petrol car is a fossil car
class PetrolCar extends FossilCar implements Refuelables{
public PetrolCar(float fuel) { this.fuel = fuel; }
@Override
public float getMileage() { /* some complex logic*/ return 10f; }
@Override
public float calculateRange() { return this.getMileage() * this.fuel; }
}
// Diesel car is a fossil car
class DieselCar extends FossilCar {
public DieselCar(float fuel) { this.fuel = fuel; }
@Override
public float getMileage() { /* some complex logic*/ return 15; }
@Override
public float calculateRange() { return this.getMileage() * this.fuel; }
}
// Electric car is a car
abstract class ElectricCar extends Car { float battery; }
// Fixed battery car is an electric car
class FixedBatteryCar extends ElectricCar {
public FixedBatteryCar(float battery) { this.battery = battery; }
@Override
float calculateRange() { /* some complex logic */ return this.battery * 8f; }
}
// Fixed battery car is an electric car
class SwappableBatteryCar extends ElectricCar {
public SwappableBatteryCar(float battery) { this.battery = battery; }
@Override
float calculateRange() { /* some other complex logic */ return this.battery * 6f; }
}
// TripPlanner class uses Car
class TripPlanner {
public float getRange(Car car){ return car.calculateRange(); }
}
public class LSP {
public static void main(String[] args) {
Car petrolCar = new PetrolCar(10);
Car dieselCar = new DieselCar(10);
Car teslaCar = new FixedBatteryCar(10);
Car rivionCar = new SwappableBatteryCar(10);
TripPlanner trip = new TripPlanner();
System.out.println("This petrol car can go: " + trip.getRange(petrolCar));
System.out.println("This diesel car can go: " + trip.getRange(dieselCar));
System.out.println("This Tesla car can go : " + trip.getRange(teslaCar));
System.out.println("This Rivian car can go: " + trip.getRange(rivionCar));
}
}
@krohit-bkk
Copy link
Author

image

@krohit-bkk
Copy link
Author

Program output:

This petrol car can go: 100.0
This diesel car can go: 150.0
This Tesla car can go : 80.0
This Rivian car can go: 60.0

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment