Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 14

Abstract Classes and Methods

Recommended resources

Welcome to the next step in our journey through Object-Oriented Programming in Java. In our last lesson, we saw how runtime polymorphism allows us to use a general superclass reference to work with specific subclass objects, deferring the choice of which method to execute until runtime. We used an Animal superclass to handle Dog and Cat objects. This raises a thoughtful question: does it ever make sense to create an object of type Animal itself? An "animal" is a concept, while a "dog" or a "cat" is a concrete entity.

This lesson addresses that exact scenario. We will explore abstract classes and abstract methods, which are Java's tools for creating non-instantiable blueprints. You'll learn how to define a class that serves purely as a template for its subclasses, enforcing a common structure and set of behaviors that must be implemented. This is a fundamental technique for building flexible and scalable software architectures, moving from just writing code to designing systems.

1. What Are Abstract Classes? The Un-creatable Blueprint

An abstract class is a special type of class that cannot be used to create objects. Its purpose is to serve as a base or a blueprint for other classes to inherit from. Think of it as a conceptual category that is too general to exist on its own.

The Coding with John channel offers a concise explanation for why you would want to make a class abstract.

Abstract Classes and Methods in Java Explained in 7 Minutes

This short segment introduces the core idea behind abstract classes and answers the crucial "why" question using the familiar Animal analogy.

Watch from the beginning until the main explanation. The key takeaway is that some parent classes, like Animal, are designed for inheritance and polymorphism, not for direct instantiation.

As the video explains, you make a class abstract by adding the abstract keyword to its declaration.

// This is an abstract class. You cannot do 'new Shape();'
public abstract class Shape {
    // It can have fields
    String color;

    // It can also have concrete (implemented) methods
    public String getColor() {
        return color;
    }
    
    // It can also have abstract methods (more on this next)
    public abstract double calculateArea(); 
}

The primary rules for an abstract class are straightforward:

  1. You declare it using the abstract keyword.
  2. It cannot be instantiated. The compiler will give you an error if you try.
  3. It can contain a mix of regular methods (with bodies) and abstract methods (without bodies).
  4. It can have fields, constructors, and static methods, just like a regular class.

Let's quickly review the formal definitions and syntax from a textual resource.

Java Abstract Class and Method (With Example)

This article from Programiz clearly lays out the fundamental rules and syntax for both abstract classes and methods.

Read the sections "Java Abstract Class" and "Java Abstract Method". This will solidify the syntax and the critical rule: if a class contains even one abstract method, the class itself must be declared abstract.


2. Abstract Methods: The Enforced Contract

The real power of abstract classes comes from abstract methods. An abstract method is a method that is declared without an implementation—it has no method body ({...}). It acts as a mandatory contract for any non-abstract (or "concrete") subclass.

public abstract void draw(); // Notice the semicolon instead of curly braces.

By including an abstract method in your abstract class, you are telling the Java compiler: "Any concrete class that inherits from me must provide its own implementation for this method."

This is a powerful design tool. It guarantees that all subclasses of a certain type will have a specific capability, even if each one implements it differently. The Telusko channel provides a very clear, step-by-step exploration of this concept.

#61 Abstract Keyword in Java

This video walks through the thought process of why you'd declare a method as abstract and the consequences of doing so.

Please watch these two key segments: Declaring an abstract method: This part explains the problem of having a method you know should exist (drive in a Car) but can't implement in the general class. It shows how this forces the method and the class to become abstract. Subclass responsibilities: This section demonstrates that you cannot create an object of the abstract class and that any concrete subclass (WagonR) must provide an implementation for the inherited abstract method.

As you saw in the video, this creates a strong contract. If a subclass inherits from an abstract class but fails to implement all of its abstract methods, the subclass must also be declared abstract. The responsibility is simply passed down the inheritance chain until a concrete class finally provides the implementation.


3. A Practical Example: The Payment System

Let's apply these concepts to a real-world scenario that you might encounter as a software developer. Imagine you're building an e-commerce platform. The platform needs to support multiple payment methods: Credit Card, UPI, Debit Card, etc. This is a perfect use case for abstraction.

The article "Abstraction in Java with real world examples" on Medium provides an excellent code example.

Abstraction in Java with real world examples | by Hari Prasad

This article uses a Payment class hierarchy to demonstrate abstraction in a very practical and relatable context.

Start by reading the introduction from the beginning to understand the motivation. Then, study the main code example carefully.

Let's break down the design from the article:

  • abstract class Payment: It's the blueprint. You can't create a generic Payment object. It defines the concept.
  • abstract void processPayment(double amount): This is the contract. It states that every form of payment must have a way to be processed, but it leaves the "how" up to the specific payment types.
  • class CreditCardPayment extends Payment: This is a concrete subclass. It fulfills the contract by providing a specific implementation for processPayment. The same applies to UpiPayment and DebitCardPayment.

The main method in the example beautifully ties this back to our previous lesson on polymorphism:

Payment payment; // A reference of the abstract superclass type

payment = new CreditCardPayment(); // Pointing to a concrete subclass object
payment.processPayment(1500);      // Calls the CreditCardPayment version

payment = new UpiPayment();        // Pointing to another concrete subclass object
payment.processPayment(800);       // Calls the UpiPayment version

This is the essence of good object-oriented design: programming to an abstraction (Payment), not a concrete implementation.


4. Summarizing the Key Differences

It's important to be clear on the distinction between an abstract class and an abstract method. They are related but serve different functions. An abstract method can only exist inside an abstract class.

This infographic provides a concise summary of their roles.

This table compares the definition, location, purpose, and rules for abstract classes and abstract methods. An abstract class is a blueprint that can contain both abstract and concrete methods, while an abstract method is a contract within that blueprint that must be implemented by subclasses.

The key relationship is that an abstract method defines a mandatory behavior, and an abstract class is the vehicle for carrying that contract (and other shared code) to its subclasses.


Conclusion

In this lesson, we've unlocked a crucial tool for object-oriented design in Java. By defining abstract classes and methods, you can create robust and extensible class hierarchies. This approach allows you to establish a common blueprint and enforce a contract that all related objects must follow, all while enabling the power of polymorphism.

Here are the main takeaways:

  • Abstract Class: A class declared with the abstract keyword that cannot be instantiated. It serves as a base for subclasses.
  • Abstract Method: A method declared with abstract that has no body. It defines a contract that concrete subclasses must implement.
  • The Golden Rule: If a class contains one or more abstract methods, the class itself must be declared abstract.
  • The Purpose: Abstraction allows you to define a template for a group of related classes, sharing common code (in concrete methods) while enforcing specific behaviors (through abstract methods).

So far, we've seen that abstract classes are excellent for defining a common identity for a group of related classes (e.g., Dog and Cat are both Animals). But what if you want to define a common capability for classes that are otherwise unrelated? For example, both a Bird and an Airplane can fly(), but they don't share a common "is-a" relationship. For this, Java provides another powerful tool: interfaces. In our next lesson, we will explore interfaces and compare them directly with abstract classes.