Task 1 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 — abstract and concrete methods

Lesson

A partly finished class

An abstract class sits between a normal class and an interface. It can hold fields and finished (concrete) methods like any class, but it can also declare abstract methods — a signature with no body, marked abstract, which every subclass must implement. Because it is unfinished, an abstract class cannot be instantiated: new Shape(...) is a compile error.


Worked example

abstract class Shape {
    private String name;
    public String getName() { return name; }    // concrete: shared code
    public abstract double area();               // abstract: each subclass decides
}

class Circle extends Shape {
    public double area() { return 3.14 * r * r; }   // must implement
}

Shape s = new Shape("X");   // ERROR: Shape is abstract; cannot be instantiated

Circle inherits getName() for free and supplies its own area().


▶ Try it: run this — Circle provides area() and inherits getName() from the abstract class.



An abstract method is...


What happens with new Shape("X") when Shape is abstract?


Type exactly what this program prints.

abstract class Shape {
    public abstract double area();
    public String label(){ return "area=" + area(); }
}
class Sq extends Shape { public double area(){ return 4.0; } }
public class Main { public static void main(String[] a){
    System.out.println(new Sq().label());
}}

Unlike an interface, an abstract class can have...


True or false?