Default Methods
Completed
Create interface Discount with double apply(double price) and a Java 8 default method String label() returning discount. Implement Percent(p) (overrides label to P% off) and Flat(amount) (keeps the default). Read a price and discounts and print each final price and label.
Input
Line 1: price. Line 2: n. Then lines percent P or flat A.
Output
n lines: PRICE (LABEL)
Example
Input
200 3 percent 25 flat 30 flat 500
Output
150.00 (25% off) 170.00 (discount) 0.00 (discount)
Editor
Java
Hints
default methods give interfaces a body (Java 8+).
Solution explanation
Default methods let interfaces grow without breaking every class that already implements them.
Show solution
import java.util.Scanner;
interface Discount {
double apply(double price);
default String label() {
return "discount";
}
}
class Percent implements Discount {
final int p;
Percent(int p) { this.p = p; }
public double apply(double price) { return price * (100 - p) / 100; }
public String label() { return p + "% off"; }
}
class Flat implements Discount {
final double amount;
Flat(double amount) { this.amount = amount; }
public double apply(double price) { return Math.max(0, price - amount); }
}
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
double price = sc.nextDouble();
int n = sc.nextInt();
for (int i = 0; i < n; i++) {
String kind = sc.next();
Discount d = kind.equals("percent") ? new Percent(sc.nextInt()) : new Flat(sc.nextDouble());
System.out.printf("%.2f (%s)%n", d.apply(price), d.label());
}
}
}