CJCoding With Joseph
15free / daySign inCreate account

Mastering Java - Full Guide

Abstract Classes

Everything On Classes

In the last section, we learned how to use inheritance to build new classes based on existing ones. But what if we want to force all subclasses to follow certain rules? That’s where abstract classes come in.


What Is an Abstract Class?

An abstract class is like a partially-built template. You can’t create an object from it directly, but other classes can extend it and fill in the missing pieces. Think of it like a contract: if a class extends an abstract class, it must follow the rules set by that abstract class.

In Java, you use the abstract keyword to create one:

public abstract class BankAccount {
    protected String name;
    protected int accountNumber;
    protected double balance;

    public BankAccount(String name, int accountNumber, double balance) {
        this.name = name;
        this.accountNumber = accountNumber;
        this.balance = balance;
    }

    public void deposit(double amount) {
        this.balance += amount;
    }

    public void withdraw(double amount) {
        this.balance -= amount;
    }

    // Abstract Methods
    public abstract void monthlyUpdate();
    public abstract String getAccountType();
}
Members only

Keep reading this lesson

You've reached the end of the free preview. Unlock the rest of this lesson plus 14 more lessons in Mastering Java - Full Guide.

  • Unlimited coding questions
  • Unlimited access to all classroom material
  • Weekly live call for questions and guidance
  • 3,000 AI tutor tokens / month
  • Personal SQL database (3 MB)
  • Progress tracking

Cancel any time.