Model delivery partners – Bike (₹20 + ₹6/km), Cycle (₹15 + ₹4/km, max 5 km) and Drone (₹50 flat, max 3 kg) – each overriding canDeliver and fee; pick the cheapest partner for several orders.
Solution
Main.java
import java.util.Comparator;
import java.util.List;
import java.util.Optional;
abstract class Partner {
abstract String name();
abstract boolean canDeliver(double km, double kg);
abstract double fee(double km, double kg);
}
class Bike extends Partner {
String name() { return "Bike"; }
boolean canDeliver(double km, double kg) { return kg <= 15; }
double fee(double km, double kg) { return 20 + 6 * km; }
}
class Cycle extends Partner {
String name() { return "Cycle"; }
boolean canDeliver(double km, double kg) { return km <= 5 && kg <= 8; }
double fee(double km, double kg) { return 15 + 4 * km; }
}
class Drone extends Partner {
String name() { return "Drone"; }
boolean canDeliver(double km, double kg) { return kg <= 3 && km <= 10; }
double fee(double km, double kg) { return 50; }
}
public class Main {
static String cheapest(List<Partner> partners, double km, double kg) {
Optional<Partner> best = partners.stream().filter(p -> p.canDeliver(km, kg)).min(Comparator.comparingDouble(p -> p.fee(km, kg)));
return best.map(p -> p.name() + " Rs " + p.fee(km, kg)).orElse("no partner");
}
public static void main(String[] args) {
List<Partner> partners = List.of(new Bike(), new Cycle(), new Drone());
double[][] orders = {{2, 1}, {4, 6}, {9, 2}, {12, 4}, {8, 20}};
for (double[] o : orders) System.out.printf("%4.0f km %4.0f kg -> %s%n", o[0], o[1], cheapest(partners, o[0], o[1]));
}
}
Output Verified by compiling and running
2 km 1 kg -> Cycle Rs 23.0
4 km 6 kg -> Cycle Rs 31.0
9 km 2 kg -> Drone Rs 50.0
12 km 4 kg -> Bike Rs 92.0
8 km 20 kg -> no partner
The selection code only uses the Partner type; adding a new partner class needs no change to cheapest().
More Polymorphism and Method Overriding practice questions
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!
We use Google Analytics cookies to see how LearnFrenzy is used and make it better, and Google AdSense to keep it free.
No analytics or ad cookies are set until you accept. Privacy Policy
·
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!