Java
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.
Exercise 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);.
Show example solution
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);
}
}
Test yourself
-
How is an abstract class declared?
- interface class
- final class
- abstract class
- static class
Show answer
abstract class — The abstract class phrase declares an abstract class.
-
Complete the abstract class declaration
abstract ____ Shape {
String name;
}
Show answer
abstract class Shape {
String name;
}
-
Match the abstract class concepts
- abstract
- Abstraction keyword
- class
- Class keyword
- extends
- Inheritance keyword
- new
- Instantiation keyword
Next lesson: abstract methods