Task 3 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 — sharing code with subclasses

Lesson

Write once, use in every subclass

This is the real payoff: a concrete method in the abstract class can call an abstract method. The shared method is written once, in the superclass, but its behavior changes per subclass — because the abstract call resolves to the actual object's implementation.


Worked example

abstract class Shape {
    public abstract double area();
    public String describe() {
        return getName() + " has area " + area();   // calls the subclass's area()
    }
}

Shape c = new Circle(1);
Shape r = new Rect(2, 3);
System.out.println(c.describe());   // Circle has area 3.14
System.out.println(r.describe());   // Rect has area 6.0

describe() is written once, yet each shape describes itself correctly.


▶ Try it: run this — the inherited describe() plugs in each subclass's own area().



A concrete method in an abstract class can...


The shared describe() gives different results because...


Type exactly what this program prints.

abstract class Shape {
    public abstract double area();
    public String describe(){ return "area " + 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){
    System.out.println(new Sq().describe());
    System.out.println(new Tri().describe());
}}

Putting describe() in the abstract class means...


True or false?