fork download
  1. abstract class Figure {
  2. double dim1;
  3. double dim2;
  4. Figure(double a, double b) {
  5. dim1 = a;
  6. dim2 = b;
  7. }
  8. // area is now an abstract method
  9. abstract double area();
  10. }
  11. class Rectangle extends Figure {
  12. Rectangle(double a, double b) {
  13. super(a, b);
  14. }
  15. // override area for rectangle
  16. double area() {
  17. System.out.println("Inside Area for Rectangle.");
  18. return dim1 * dim2;
  19. }
  20. }
  21.  
  22. class Triangle extends Figure {
  23. Triangle(double a, double b) {
  24. super(a, b);
  25. }
  26. // override area for right triangle
  27. double area() {
  28. System.out.println("Inside Area for Triangle.");
  29. return dim1 * dim2 / 2;
  30. }
  31. }
  32.  
  33. class AbstractAreas {
  34. public static void main(String args[]) {
  35. // Figure f = new Figure(10, 10); // illegal now
  36. Rectangle r = new Rectangle(9, 5);
  37. Triangle t = new Triangle(10, 8);
  38. Figure figref; // this is OK, no object is created
  39. figref = r;
  40. System.out.println("Area is " + figref.area());
  41. figref = t;
  42. System.out.println("Area is " + figref.area());
  43. }
  44. }
Runtime error #stdin #stdout 0.02s 245632KB
stdin
Standard input is empty
stdout
Standard output is empty