Abstract Method in Java
beginner· OOP · Abstraction
Problem
An abstract method has a signature but no body — any subclass that wants to be instantiable must override it with a real implementation, or that subclass would itself have to stay abstract.
Define an abstract processPayment() method and a subclass that supplies its implementation.
Input
new CreditCardPayment().processPayment(250.0)
Output
Processing $250.0 via credit card
Java Program
Java
abstract class PaymentMethod {
abstract void processPayment(double amount); // no body — subclasses must implement this
}
class CreditCardPayment extends PaymentMethod {
void processPayment(double amount) {
System.out.println("Processing $" + amount + " via credit card");
}
}
public class AbstractMethodDemo {
public static void main(String[] args) {
PaymentMethod p = new CreditCardPayment();
p.processPayment(250.0);
}
}Output
Processing $250.0 via credit card
Core Logic
Declaring processPayment() with no body forces every concrete subclass to decide for itself what 'processing a payment' actually means.
How It Works
- 1
abstract void processPayment(double amount);declares the method's signature only — there's no implementation for any subclass to inherit. - 2
class CreditCardPayment extends PaymentMethodprovides the one required override, printing a credit-card-specific message. - 3Because
CreditCardPaymentimplements every abstract method its parent declares, it's a fully concrete class and can be instantiated withnew. - 4Calling
processPayment(250.0)on that instance runsCreditCardPayment's own implementation.
new CreditCardPayment().processPayment(250.0) prints "Processing $250.0 via credit card", the exact behavior CreditCardPayment defined.💡
Key Point: If a second subclass — say, CashPayment — didn't override processPayment(), that subclass would have to be declared abstract too; a class can only be instantiated once every abstract method it inherits has a real implementation somewhere in its chain.
Key Concepts
abstract methodmandatory overridesubclass contract