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)
01// Java program to illustrate the concept of abstraction
02public class AbstractDemo {
03  public static void main( String[ ] args ) {
04    Shape s1 = new Circle   ( args[0], Double.parseDouble( args[1] ) );
05    Shape s2 = new Rectangle( args[2], Double.parseDouble( args[3] ),
06                                       Double.parseDouble( args[4] ) );
07    System.out.print( s1.toString( ) + " " );
08    System.out.print( s2.toString( ) );
09  }
10}
Shape.java (the abstract keyword)
01abstract class Shape {
02  String color;
03 
04  // These are abstract methods.
05  abstract int area( );
06  public abstract String toString( );
07 
08  // Abstract classes can have constructors.
09  public Shape( String color ) { this.color = color; }
10 
11  // This is a concrete method.
12  public String getColor( ) { return color; }
13}
Circle.java (the abstract keyword)
01class Circle extends Shape {
02  double radius;
03  public Circle( String color, double radius ) {
04    // Calling Shape constructor
05    super( color );
06    this.radius = radius;
07  }
08  @Override
09  int area( ) { return (int) ( Math.PI * Math.pow( radius, 2 ) ); }
10  @Override
11  public String toString( ) { return super.color + " " + area( ); }
12}
Rectangle.java (the abstract keyword)
01class Rectangle extends Shape {
02  double length;
03  double width;
04 
05  public Rectangle( String color, double length, double width ) {
06    // Calling Shape constructor
07    super( color );
08    this.length = length;
09    this.width  = width;
10  }
11  @Override
12  int area( ) { return (int) ( length*width ); }
13  @Override
14  public String toString( ) { return super.getColor( ) + " " + area( ); }
15}
shell> java AbstractDemo          

Output:           Result: