Module 6: Inheritance and Polymorphism
Lesson focusAbstract Classes
Learn to create template classes that cannot be instantiated, defining common methods and fields for a group of subclasses while forcing them to provide specific implementations.
What is an Abstract Class? An abstract class is a restricted class that cannot be used to create objects (it cannot be instantiated). It serves as a blueprint for other classes. It is declared with the abstract keyword.
What is an Abstract Method? An abstract method is a method that is declared without an implementation (without braces, and followed by a semicolon). abstract void myMethod();
Key Rules:
- If a class contains one or more abstract methods, then the class itself must be declared abstract.
- If a regular class extends an abstract class, it must implement all of the abstract methods of the superclass.
- An abstract class can have both abstract and non-abstract (concrete) methods.
When to Use Abstract Classes: Use an abstract class when you want to share code among several closely related classes. It establishes a strong 'is-a' relationship and allows you to provide a common base with some default implementation and some methods that subclasses must define themselves.
Abstract Class vs. Concrete Class: A regular (concrete) class has all its methods fully implemented. An abstract class can have a mix of implemented and unimplemented (abstract) methods.
abstract class GraphicObject {
int x, y;
void moveTo(int newX, int newY) {
this.x = newX;
this.y = newY;
}
// Abstract method - must be implemented by subclasses
abstract void draw();
}
class Circle extends GraphicObject {
@Override
void draw() {
System.out.println("Drawing a circle at (" + x + ", " + y + ")");
}
}