Java abstract final class Inheritance

Question

What is the output of the following code?

abstract final class Shape {
  double width;/*from  w  w  w  .  j  av  a2  s . c  o m*/
  double height; 

  Shape(double a, double b) {
    width = a;
    height = b;
  }

  // area is now an an abstract method 
  abstract double area();
}

class Rectangle extends Shape {
  Rectangle(double a, double b) {
    super(a, b);
  }

  // override area for rectangle
  double area() {
    System.out.println("Inside Area for Rectangle.");
    return width * height;
  }
}

class Triangle extends Shape {
  Triangle(double a, double b) {
    super(a, b);
  }

  // override area for right triangle
  double area() {
    System.out.println("Inside Area for Triangle.");
    return width * height / 2;
  }
}

public class Main {
  public static void main(String args[]) {
    Rectangle r = new Rectangle(9, 5);
    Triangle t = new Triangle(10, 8);
    
    Shape figref; // this is OK, no object is created

    figref = r;
    System.out.println("Area is " + figref.area());
    
    figref = t;
    System.out.println("Area is " + figref.area());
  }
}


Compile time error
The class Shape can be either abstract or final, not both

Note

A class cannot be both abstract and final.

An abstract class has to be extended by its subclasses.




PreviousNext

Related