Abstract Classes


An abstract class can be used to define the common structure for a family of related classes. An abstract class is designated as such by including the abstract keyword in the class declaration syntax. An abstract class is merely a blueprint. You cannot create an instance of an abstract class. Abstract classes can define both abstract and concrete methods .

When a concrete (i.e., nonabstract) class is written as a subclass of an abstract class, the subclass must provide an implementation of all abstract methods defined in the abstract superclass. If you don't do this, you will get a compiler error. An abstract class can be written as a subclass of another abstract class.

Example: Using Abstract Classes

To demonstrate how abstract classes are defined and used we will write an abstract Shape class that will serve as the blueprint for 2-D geometric shapes. All 2-D shapes will have an area and circumference associated with them. The Shape class declares the getArea() and getCircumference() methods for returning these properties. Note that the method declarations are terminated with semicolons.

 public abstract class Shape {   abstract double getArea();   abstract double getCircumference(); } 

Next, we will write a subclass of the Shape class named Rectangle . The Rectangle class encapsulates a rectangular shape as you might have guessed. Because Rectangle is a subclass of Shape , the Rectangle class must provide an implementation of the getArea() and getCircumference() methods. The way it implements those methods is not specified. If you defined a Circle class, the Circle class implementation of getArea() and getCircumference() would be different than the Rectangle class implementation.

 public class Rectangle extends Shape {   private double width, height;   public Rectangle(double w, double h) {     width = w;     height = h;   }   //  The Rectangle class must implement the   //  abstract methods from the Shape class   public double getArea() {     return width*height;   }   public double getCircumference() {     return 2.0*(width+height);   }   public static void main(String args[]) {     Rectangle rect = new Rectangle(2.0,3.0);     System.out.println("area is " + rect.getArea());     System.out.println("circumference is " +                            rect.getCircumference());   } } 

Output ”

 area is 6.0 circumference is 10.0 


Technical Java. Applications for Science and Engineering
Technical Java: Applications for Science and Engineering
ISBN: 0131018159
EAN: 2147483647
Year: 2003
Pages: 281
Authors: Grant Palmer

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net