Skip to content

Instantly share code, notes, and snippets.

@krohit-bkk
Created January 20, 2024 17:16
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/d1981902f723e2ac70937420e0fd0e04 to your computer and use it in GitHub Desktop.
Save krohit-bkk/d1981902f723e2ac70937420e0fd0e04 to your computer and use it in GitHub Desktop.
Code snippet 1 for Loskov Substitution Principle
// Enforce cars to have method to return mileage
interface Refuelables {
float getMileage();
}
// Car has mileage
abstract class Car implements Refuelables {
float fuel;
abstract float calculateRange();
}
// Petrol car is a car
class PetrolCar extends Car {
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 car
class DieselCar extends Car {
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; }
}
// TripPlanner class uses Car
class TripPlanner {
public float getRange(Car car){ return car.calculateRange(); }
}
// Press Shift twice to open the Search Everywhere dialog and type `show whitespaces`,
// then press Enter. You can now see whitespace characters in your code.
public class OcpOnly {
public static void main(String[] args) {
Car petrolCar = new PetrolCar(10);
Car dieselCar = new DieselCar(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));
}
}
@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

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