public abstract class Shape {
public abstract double area();
}
public class Sq extends Shape {
private double s;
public Sq(double x) { s = x; }
public double area() { return s * s; }
}
public class Tri extends Shape {
private double b, h;
public Tri(double bb, double hh) { b = bb; h = hh; }
public double area() { return 0.5 * b * h; }
}
// Usage:
ArrayList<Shape> shapes = new ArrayList<Shape>();
shapes.add(new Sq(2));
shapes.add(new Tri(4, 3));
double total = 0;
for (int i = 0; i < shapes.size(); i++) {
total += shapes.get(i).area();
}
System.out.print(total);What is printed?
- A
6.0
- B
4.0
- C
Compile error
- Dcheck_circle
10.0
Explanation
Sq(2).area = 4; Tri(4, 3).area = 6. Total = 10.0.