CodeBlanks Logo Icon CodeBlanks

abstract class

Learn to define abstract classes.

What is an abstract class?

An abstract class is a base class that cannot be instantiated directly. It is defined with the abstract keyword. It acts as a template for subclasses and gathers shared fields and methods.

Example: abstract class Shape { }. Here Shape is abstract; writing new Shape() gives a compile error. But you can write class Circle extends Shape { }. An abstract class defines common behavior that concrete classes cannot carry. A subclass inherits the abstract class body with extends. This mechanism reduces code duplication and keeps the hierarchy tidy. The base class only provides the template.

Instantiating an abstract class

You cannot create an instance of an abstract class with new. Java prevents you from instantiating an abstract type. You must first write a subclass and instantiate that.

Example: if you define abstract class Animal { }, then new Animal() gives a compile error. But you can write class Dog extends Animal { } and then new Dog(). This restriction ensures the abstract class remains only a base; it cannot be used on its own. A subclass fills in the template the abstract class provides. This helps the hierarchy stay meaningful. If you want to instantiate directly, do not make the class abstract.

Practice Define the Shape abstract class

Define an abstract class Shape. Add a String name field and a constructor Shape(String name) that assigns the field. Write class Circle extends Shape; its constructor Circle(String name) calls the parent constructor with super(name). In main create Circle c = new Circle("Circle"); and run System.out.println(c.name);.

Starter code

Main.java
// Define the abstract geometry class
// Add a subclass
// Instantiate the subclass and print in main

Sample solution

Main.java
abstract class Shape {
    String name;
    Shape(String name) {
        this.name = name;
    }
}
class Circle extends Shape {
    Circle(String name) {
        super(name);
    }
}
class Main {
    public static void main(String[] args) {
        Circle c = new Circle("Circle");
        System.out.println(c.name);
    }
}

Expected output

Circle

Questions and answers

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

1 How is an abstract class declared?

  • interface class
  • final class
  • abstract class Correct answer
  • static class

Explanation: The abstract class phrase declares an abstract class.

2 Complete the abstract class declaration

Question
abstract ____ Shape {
    String name;
}
Answer
abstract class Shape {
    String name;
}

Explanation: abstract class declares an abstract class.

3 Match the abstract class concepts

Term Meaning
abstract Abstraction keyword
class Class keyword
extends Inheritance keyword
new Instantiation keyword

All lessons in Intermediate