blikk info infothek forum galerie sitemap

Abstrakte Klassen und Methoden

zur Aufgabenstellung

public abstract class Shape {

public abstract double area();

public abstract double circumference();



}

public class Circle extends Shape {

protected double r;

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

public Circle() { this(1.0); }

public double area() { return Math.PI*r*r; }

public double circumference() { return 2*Math.PI*r; }

public double getRadius() { return r; }

}

public class Rectangle extends Shape {

protected double w, h;

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

public Rectangle() { this(1.0,1.0); }

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

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

public double getWidth() { return w; }

public double getHeight() { return h; }

}

Aufruf:

public static void main(String[] args){

Shape[] aShape = new Shape[2];

aShape[0] = new Circle (2.0);

aShape[1] = new Rectangle (1.0,2.0);

double area = 0.0;

for (int i = 0; i < aShape.length; i++)

area += aShape[i].area();

}

nach oben