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 classShapepossible. -
Meaningful implementations exist both in subclass
RectangleandCircle.
Solution: Abstract method
getArea() in superclass
Shape.
abstract❶ public class Shape { /** * Calculate the shape's area. * @return The shape's area */ abstract❷ public double getArea()❸; ... |
|||
public class Rectangle extends Shape {
@Override❶
public double getArea() {
return width * height;
}
... |
public class Circle ... {
@Override❶
public double getArea() {
return Math.PI *
radius * radius;
}
... |
||
|
Superclass NoteYou cannot create instances of |
|
|
Method In other words: The |
|
|
An |
|
|
Both |
final Shape s =
new Shape(1., 2.); // Error: '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
abstractmethod must itself be declaredabstract. -
abstractclasses are allowed to host non-abstractmethods. -
A class may be declared
abstractirrespective of purely containing non-abstractmethods.
