Abstract methods
|
|
final Shape[] shapes ❶ = { new Circle(1, 1, 2.) ❷, new Rectangle(1, -1, 2., 3.)❷}; for (final Shape s : shapes) { System.out.println(s.toString() + ": area = " + s.getArea()); ❸ }
Circle at (1.0|1.0), radius= 2.0: area = 12.566370614359172 Rectangle at (1.0|-1.0), width= 2.0, height=3.0: area = 6.0
An array of |
|
A |
|
Polymorphic dispatch: Depending on the object's type the Java™ runtime will automatically choose either
|
-
No meaningful
getArea()
method in classShape
possible. -
Meaningful implementations exist both in subclass
Rectangle
andCircle
.
Solution: Abstract method getArea()
in
superclass Shape
.
|
|||
|
|
Superclass NoteYou cannot create instances of |
|
Method In other words: The |
|
An |
|
Both |
final Shape s =
new Shape(1., 2.); // 'Shape' is abstract; cannot be instantiated
// Error: Class 'Circle' must either be declared abstract or // implement abstract method 'getArea()' in 'Shape' public class Circle extends Shape { public Circle(double x,double y, double radius) { super(x, y); this.radius = radius; } private double radius; }
-
A class containing an
abstract
method must itself be declaredabstract
. -
abstract
classes are allowed to host non-abstract
methods. -
A class may be declared
abstract
irrespective of purely containing non-abstract
methods.