Inheritance in Java
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
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);
}
}Navika: Rs. 12480How it works
Account(lines 2 to 12) is the parent (superclass, base class).- Line 14:
SavingsAccount extends Accountmakes it a child (subclass, derived class). It inheritsholder,balanceanddeposit. - Line 18:
super(holder, balance)runs the parent's constructor to set up the inherited part (see "Java Super Keyword"). - The child adds its own field
ratePercentand methodaddInterest. 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:
| Statement | True? | Inheritance? |
|---|---|---|
| A savings account is an account | Yes | SavingsAccount extends Account |
| A manager is an employee | Yes | Manager extends Employee |
| A car is an engine | No: a car has an engine | Use a field instead (see "Composition vs Inheritance") |
What Is and Isn't Inherited
| Member of the parent | Inherited by the child? |
|---|---|
public and protected fields and methods | Yes |
| Package-private members (no modifier) | Yes, if the child is in the same package |
private fields and methods | Not accessible. They exist in the object, but the child can't use them directly |
| Constructors | No. The child calls them with super(...) |
static members | Accessible through the child, but they still belong to the parent |
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
- Easy: Write a
Vehicleclass withregNumberandwheels, and aCar extends Vehiclethat addsseats. - Harder: Add a
withdraw(long amount)method toAccountthat refuses to go below zero, and show thatSavingsAccountgets it automatically.
Key Takeaways
Was this tutorial helpful?