Task 5 of 7 · 0 solved · 7 to go0%
You can read the problem, but answers are checked only for signed-in students. Sign in to answer →

8.3 Abstract classes — the abstract type in use

Lesson

An abstract class is still a type

Even though you cannot instantiate it, an abstract class is a type: you can declare Shape s = new Circle(1);, build a Shape[] of mixed subclasses, and take a Shape parameter. Calling area() or describe() dispatches to the actual object — the same polymorphism as before.


Worked example

Shape[] shapes = { new Circle(1), new Rect(2, 3) };
for (int i = 0; i < shapes.length; i++) {
    System.out.println(shapes[i].describe());
}
// Circle has area 3.14
// Rect has area 6.0

The array is typed Shape, but each element behaves as its real class.


▶ Try it: run this — one loop over an abstract type, two different areas.



Can a variable have an abstract class type?


A Shape[] where Shape is abstract can hold...


Type exactly what this program prints.

abstract class Shape { public abstract double area(); }
class Sq extends Shape { public double area(){ return 4.0; } }
class Tri extends Shape { public double area(){ return 6.0; } }
public class Main { public static void main(String[] a){
    Shape[] arr = { new Sq(), new Tri() };
    for (int i = 0; i < arr.length; i++) System.out.println(arr[i].area());
}}

Match each feature to where it belongs.


True or false?