Abstraction (Cont.)


An Abstraction Example
Consider a classic “shape” example, perhaps used in a computer-aided design system or game simulation. The base type is shape and each shape has a color, size, and so on. From this, specific types of shapes are derived (inherited)—circle, square, triangle, and so on—each of which may have additional characteristics and behaviors.

For example, some behaviors may be different, such as the area of a shape. The type hierarchy embodies both the similarities and differences between the shapes. Note that the type of area has been changed from double to int.

AbstractDemo.java (the abstract keyword)
// Java program to illustrate the concept of abstraction 
public class AbstractDemo {
  public static void main( String[ ] args ) {
    Shape s1 = new Circle   ( args[0], Double.parseDouble( args[1] ) );
    Shape s2 = new Rectangle( args[2], Double.parseDouble( args[3] ),
                                       Double.parseDouble( args[4] ) );
    System.out.print( s1.toString( ) + " " );
    System.out.print( s2.toString( ) );
  }
}
Shape.java (the abstract keyword)
abstract class Shape {
  String color;

  // These are abstract methods.
  abstract int area( );
  public abstract String toString( );

  // Abstract classes can have constructors.
  public Shape( String color ) { this.color = color; }

  // This is a concrete method.
  public String getColor( ) { return color; }
}
Circle.java (the abstract keyword)
class Circle extends Shape {
  double radius;
  public Circle( String color, double radius ) {
    // Calling Shape constructor
    super( color );
    this.radius = radius;
  }
  @Override
  int area( ) { return (int) ( Math.PI * Math.pow( radius, 2 ) ); }
  @Override
  public String toString( ) { return super.color + " " + area( ); }
}
Rectangle.java (the abstract keyword)
class Rectangle extends Shape {
  double length;
  double width;

  public Rectangle( String color, double length, double width ) {
    // Calling Shape constructor
    super( color );
    this.length = length;
    this.width  = width;
  }
  @Override
  int area( ) { return (int) ( length*width ); }
  @Override
  public String toString( ) { return super.getColor( ) + " " + area( ); }
}
shell> java AbstractDemo          

Output:           Result: