Achieving Abstraction in Java with real world example

import java.time.Duration;interface Bakeable {default Boolean performPreHeat() {return true;public abstract Duration cookingDuration();Integer getTemperature();}}
import java.time.Duration;
public class Oven {
public void bake(Bakeable bakeable) {turnOn();if(bakeable.performPreHeat())performPreheat();setTemperature(bakeable.getTemperature());wait(bakeable.cookingDuration());turnOff();System.out.println(“Baking complete!!”);}private void turnOn() {System.out.println(“Turning on the oven”);}private void performPreheat() {System.out.println(“Preheating the oven”);}private void setTemperature(Integer temperature) {System.out.println(“Setting the temperature to: “ + temperature);}private void wait(Duration duration) {System.out.println(“Waiting for “ + duration.toMinutes() + “ minutes”);}private void turnOff() {System.out.println(“Turning off the oven”);}}
import java.time.Duration;
public class Cake implements Bakeable{
private Integer weight;public Cake(Integer weight) {this.weight = weight;}@Overridepublic Boolean performPreHeat() {return false;}@Overridepublic Integer getTemperature() {return 240;}@Overridepublic Duration cookingDuration() {if(weight < 100)return Duration.ofMinutes(10);if(weight < 500)return Duration.ofMinutes(30);if(weight < 750)return Duration.ofMinutes(45);return Duration.ofHours(1);}public void deliver() {boxing();System.out.println(“Cake delivered!”);}private void boxing() {System.out.println(“Cake boxed!”);}}
public class Bakery {public static void main(String args[]) {Bakeable cake = new Cake(300);Oven oven = new Oven();oven.bake(cake);cake.deliver();}}

--

--

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