Skip to main content
Beginnerconceptual

Explain inheritance with a real-world example, and the types of inheritance supported in Java.

ReportedSource: GeeksforGeeks interview experience: Accenture Associate Software Engineer

Quick answer

Child classes reuse and extend a parent (is-a), e.g. SavingsAccount/CurrentAccount extending Account. Java supports single, multilevel and hierarchical class inheritance; multiple inheritance only via interfaces.

Inheritance lets a class (child) acquire the fields and methods of another (parent), modelling an is-a relationship and enabling reuse and polymorphism.

Real-world example. A bank's Account has accountNumber, balance, deposit(), withdraw(). SavingsAccount and CurrentAccount extend it: savings adds interestRate and addInterest(); current overrides withdraw() to allow an overdraft.

Main.java
class Account {
  protected double balance;
  void deposit(double amt) { balance += amt; }
  void withdraw(double amt) { if (amt <= balance) balance -= amt; }
}
class CurrentAccount extends Account {
  double overdraft = 10000;
  @Override void withdraw(double amt) {
    if (amt <= balance + overdraft) balance -= amt;
  }
}

Types in Java. Single, multilevel (A -> B -> C) and hierarchical (B and C extend A) through classes. Multiple inheritance of classes is not allowed (avoids the diamond problem), but a class can implement multiple interfaces, including default methods.

Good design notes. Use super to call the parent constructor/method; prefer composition when the relationship is has-a rather than is-a.

Discussion