Java: Abstract class

Java lets us define a method without implementing it by declaring the method with the abstract modifier.

An abstract method has no body; it simply has a signature definition followed by a semicolon.

package javaapplication41;

public class MainShape {

    public abstract class Shape {

        public abstract double area();            // Abstract methods: note

        public abstract double circumference();   // semicolon instead of body.
    }

    static class Circle extends Shape {

        public static final double PI = 3.14159265358979323846;
        protected double r;                              // Instance data

        public Circle(double r) {
            this.r = r;
        }          // Constructor

        public double getRadius() {
            return r;
        }          // Accessor

        public double area() {
            return PI * r * r;
        }          // Implementations of

        public double circumference() {
            return 2 * PI * r;
        } // abstract methods.
    }

    static class Rectangle extends Shape {

        protected double w, h;                               // Instance data

        public Rectangle(double w, double h) {               // Constructor
            this.w = w;
            this.h = h;
        }

        public double getWidth() {
            return w;
        }               // Accessor method

        public double getHeight() {
            return h;
        }              // Another accessor

        public double area() {
            return w * h;
        }                 // Implementation of

        public double circumference() {
            return 2 * (w + h);
        }  // abstract methods
    }

    public static void main(String[] args) {

        Shape[] shapes = new Shape[3];

        shapes[0] = new Circle(2.0);
        shapes[1] = new Rectangle(1.0, 3.0);
        shapes[2] = new Rectangle(4.0, 2.0);

        double totalArea = 0;
        for (int i = 0; i < shapes.length; i++) {
            totalArea += shapes[i].area();
            System.out.println(totalArea);
        }
    }
}

abstract

Series Navigation<< Java: Rules for accessing members
Java: An array of objects >>