Inheritance in Java

Naveen AnamaneniUpdated · 5 min read

A bank has savings accounts and current accounts. Both have a holder, a balance, deposits and withdrawals. A savings account also earns interest; a current account allows an overdraft. Writing all the shared parts twice would mean fixing every bug twice. Inheritance lets you write the shared parts once, in a parent class, and build each special kind of account on top of it with the keyword extends.

A Parent and a Child

A subclass inherits the parent's members and adds its own
Bank.java▶ Try it
public class Bank {
    static class Account {
        String holder;
        long balance;
 
        Account(String holder, long balance) {
            this.holder = holder;
            this.balance = balance;
        }
 
        void deposit(long amount) { balance += amount; }
    }
 
    static class SavingsAccount extends Account {
        double ratePercent;
 
        SavingsAccount(String holder, long balance, double ratePercent) {
            super(holder, balance);
            this.ratePercent = ratePercent;
        }
 
        void addInterest() { balance += (long) (balance * ratePercent / 100); }
    }
 
    public static void main(String[] args) {
        SavingsAccount s = new SavingsAccount("Navika", 10000, 4.0);
        s.deposit(2000);
        s.addInterest();
        System.out.println(s.holder + ": Rs. " + s.balance);
    }
}
Output
Navika: Rs. 12480

How it works

  1. Account (lines 2 to 12) is the parent (superclass, base class).
  2. Line 14: SavingsAccount extends Account makes it a child (subclass, derived class). It inherits holder, balance and deposit.
  3. Line 18: super(holder, balance) runs the parent's constructor to set up the inherited part (see "Java Super Keyword").
  4. The child adds its own field ratePercent and method addInterest.
  5. s.deposit(2000) uses the inherited method: 10,000 + 2,000 = 12,000; 4% interest adds 480.

Try it yourself: write CurrentAccount extends Account with an overdraftLimit field, and create one for Srihitha.

The Is-A Test

Use inheritance only when the child is a kind of parent:

StatementTrue?Inheritance?
A savings account is an accountYesSavingsAccount extends Account
A manager is an employeeYesManager extends Employee
A car is an engineNo: a car has an engineUse a field instead (see "Composition vs Inheritance")

What Is and Isn't Inherited

Member of the parentInherited by the child?
public and protected fields and methodsYes
Package-private members (no modifier)Yes, if the child is in the same package
private fields and methodsNot accessible. They exist in the object, but the child can't use them directly
ConstructorsNo. The child calls them with super(...)
static membersAccessible through the child, but they still belong to the parent
Compiler output
Priv.java:2: error: balance has private access in Account
class Savings extends Account { long get() { return balance; } }
                                                    ^

That's why parent classes often use protected for fields their children need, or offer protected or public methods to reach private data (see "Access Modifiers in Java").

Every Class Extends Object

A class without extends automatically extends java.lang.Object, the root of every class hierarchy. That's why every object has toString(), equals() and hashCode(), which the Object Class chapter covers. new Account(...).getClass().getSuperclass() prints class java.lang.Object.

Common Mistakes

Using inheritance just to reuse code. If the child isn't really a kind of the parent, use composition.

Expecting to use the parent's private fields. They're not accessible; use protected or methods.

Forgetting super(...) when the parent has no no-arg constructor. The child's constructor doesn't compile (see "Constructor Calls in Inheritance").

Interview Corner

What is inheritance in Java?

Inheritance lets a class (the subclass) acquire the fields and methods of another class (the superclass) with extends, then add new members or override inherited methods. It models an is-a relationship and lets shared code live in one place. Java supports single inheritance of classes; every class ultimately extends Object.

Are constructors and private members inherited?

Constructors are not inherited; a subclass calls them with super(...). Private fields and methods are part of the object but are not accessible from the subclass's code.

Practice

  1. Easy: Write a Vehicle class with regNumber and wheels, and a Car extends Vehicle that adds seats.
  2. Harder: Add a withdraw(long amount) method to Account that refuses to go below zero, and show that SavingsAccount gets it automatically.

Quick check: Inheritance

4 questions
1Which keyword makes one class inherit from another?
2Which parent members can the child NOT use directly?
3What does a class extend if it has no extends?
4Which pair is a good fit for inheritance?

Key Takeaways

Was this tutorial helpful?

Lesson 112 of 482