Created
January 20, 2024 17:16
-
-
Save krohit-bkk/d1981902f723e2ac70937420e0fd0e04 to your computer and use it in GitHub Desktop.
Code snippet 1 for Loskov Substitution Principle
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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)); | |
} | |
} |
Author
krohit-bkk
commented
Jan 20, 2024
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