CodeBlanks Logo Icon CodeBlanks

Abstract reference

Learn to use objects via abstract references.

Abstract class references

An abstract class cannot be instantiated directly, but it works as a reference type. Shape s = new Circle(); is valid when Shape is abstract; this is the most powerful use. The abstract class provides a contract; subclasses supply concrete behavior.

Adding a new subclass does not change code that uses the superclass. A method process(Shape s) can receive a Circle, a Square or any future subclass; each calls the right area method.

Polymorphism with interfaces

An interface can also be a reference type. Drawable d = new Circle(); works when Circle implements Drawable. This lets you set a type contract independent of the class hierarchy.

You can implement several interfaces with implements A, B, C; this is Java's answer to multiple inheritance. Interfaces may have default methods with bodies.

Practice Abstract Shape and concrete Circle

Define abstract class Shape with an abstract int area(); method (no body). Define class Circle extends Shape with an int r field, a Circle(int r) constructor and an overridden area method returning r * r * 3. In main, assign with Shape s = new Circle(3); and print System.out.println("Area: " + s.area());.

Starter code

Main.java
// abstract Shape class: declare a bodiless area method

// Circle extends Shape; r field, constructor and area method

// main: assign a Circle instance as Shape and print

Sample solution

Main.java
abstract class Shape {
    abstract int area();
}

class Circle extends Shape {
    int r;
    Circle(int r) { this.r = r; }
    int area() { return r * r * 3; }
}

public class Main {
    public static void main(String[] args) {
        Shape s = new Circle(3);
        System.out.println("Area: " + s.area());
    }
}

Expected output

Area: 27

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Match the abstract and concrete uses

Term Meaning
abstract class Cannot be instantiated; holds references
new Circle() Produces a concrete instance
interface Contract; allows multiple inheritance
concrete class Created directly with new

2 Which is true for an abstract class?

  • It can be instantiated directly with new
  • It can only contain static methods
  • It cannot be replaced by an interface
  • It cannot be instantiated but can be a reference type Correct answer

Explanation: An abstract class cannot be instantiated but can be used as a reference.

3 Complete the interface implementation keyword

Question
class Circle extends Shape implements ____ {
    public void draw() { }
}
Answer
class Circle extends Shape implements Drawable {
    public void draw() { }
}

Explanation: Circle implements the Drawable interface.

All lessons in Intermediate