Java code to convert given input values from KM to Meter, Meter to Centimetres, etc. OOP approach using the strategy design pattern Step 1: Define an interface.
1 2 3 4 5 | package com.oop.eg2; public interface Converter<T> { T convert(T input); |
Step 2: Define a generic “MyMetricConverter” that implements the “Converter”.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | package com.oop.eg2; import java.math.BigDecimal; public abstract class MyMetricConverter implements Converter<Double> { @Override public Double convert(Double input) { BigDecimal result = BigDecimal.valueOf(input).multiply(BigDecimal.valueOf(getConversionRate())); return result.doubleValue(); } abstract double getConversionRate(); } |
Step…