Inheritance in Java – Types, Rules and Examples
Inheritance is the OOP mechanism by which one class acquires the fields and methods of another. The class that is inherited from is the superclass (parent, base class); the class that inherits is the subclass (child, derived class). In Java, a class inherits with the extends keyword, forming an IS-A relationship: a Manager is an Employee.
Inheritance enables code reuse and is the foundation of runtime polymorphism. This tutorial covers the syntax, what is and is not inherited, the types of inheritance, why Java has no multiple class inheritance, constructor order, and when to prefer composition.
1. Syntax and a First Example
class SubClass extends SuperClass {
// inherits SuperClass's accessible fields and methods
// can add new members and override inherited methods
}
public class InheritanceBasics {
static class Employee { // superclass (parent)
protected final String name;
protected final double salary;
Employee(String name, double salary) {
this.name = name;
this.salary = salary;
}
double annualPay() { return salary * 12; }
String describe() { return name + " earns " + annualPay() + " per year"; }
}
static class Manager extends Employee { // subclass (child) IS-A Employee
private final double bonus;
Manager(String name, double salary, double bonus) {
super(name, salary); // initialise the inherited part first
this.bonus = bonus;
}
@Override double annualPay() { return super.annualPay() + bonus; } // specialise
void approveLeave(String who) { System.out.println(name + " approved leave for " + who); } // add
}
public static void main(String[] args) {
Employee dev = new Employee("Ravi", 80_000);
Manager mgr = new Manager("Asha", 120_000, 200_000);
System.out.println(dev.describe());
System.out.println(mgr.describe()); // describe() inherited, annualPay() overridden
mgr.approveLeave("Ravi");
System.out.println("Manager is an Employee? " + (mgr instanceof Employee));
}
}
Ravi earns 960000.0 per year Asha earns 1640000.0 per year Asha approved leave for Ravi Manager is an Employee? true
A subclass can do three things with what it inherits: use it as is (describe()), override it (annualPay()), and add new members (approveLeave()).
2. What Is and Is Not Inherited
public class WhatIsInherited {
static class Parent {
public String pub = "public";
protected String prot = "protected";
String pkg = "package-private";
private String priv = "private";
String getPriv() { return priv; } // private data reachable via inherited method
static String util() { return "static method"; }
}
static class Child extends Parent {
void show() {
System.out.println(pub + ", " + prot + ", " + pkg);
// System.out.println(priv); // compile error: priv has private access
System.out.println("via getter: " + getPriv());
System.out.println("static: " + util());
}
}
public static void main(String[] args) {
new Child().show();
System.out.println("Every class extends Object: " + new Child().getClass().getSuperclass().getSuperclass().getSimpleName());
}
}
public, protected, package-private via getter: private static: static method Every class extends Object: Object
| Member | Inherited? |
|---|---|
public and protected fields and methods | Yes |
| Package-private members | Only by subclasses in the same package |
private members | No (they exist in the object but are accessible only through inherited methods) |
| Constructors | No; called with super(...) |
| Static members | Accessible through the subclass, but belong to the parent; not overridden |
Every class without an extends clause implicitly extends java.lang.Object, so every object has toString(), equals(), hashCode() and the other Object methods.
3. Types of Inheritance
Single inheritance
One class extends one other class: Car extends Vehicle.
Multilevel inheritance
A chain of inheritance: SportsCar extends Car, which extends Vehicle.
Hierarchical inheritance
Several classes extend the same parent: Car and Truck both extend Vehicle.
public class InheritanceTypes {
// Single: B extends A
static class Vehicle { String move() { return "moves"; } }
static class Car extends Vehicle { String honk() { return "honks"; } }
// Multilevel: C extends B extends A
static class SportsCar extends Car { String turbo() { return "uses turbo"; } }
// Hierarchical: several classes extend the same parent
static class Truck extends Vehicle { String load() { return "carries cargo"; } }
// "Multiple" via interfaces: one class, many interfaces
interface Electric { default String charge() { return "charges"; } }
interface Autonomous { default String drive() { return "drives itself"; } }
static class RoboTaxi extends Car implements Electric, Autonomous { }
public static void main(String[] args) {
SportsCar s = new SportsCar();
System.out.println("SportsCar " + s.move() + ", " + s.honk() + ", " + s.turbo());
System.out.println("Truck " + new Truck().move() + " and " + new Truck().load());
RoboTaxi r = new RoboTaxi();
System.out.println("RoboTaxi " + r.move() + ", " + r.charge() + ", " + r.drive());
}
}
SportsCar moves, honks, uses turbo Truck moves and carries cargo RoboTaxi moves, charges, drives itself
4. Why Java Has No Multiple Class Inheritance
A class cannot extend two classes (class C extends A, B does not compile). If both parents had a method or field with the same name, which one should C inherit? This ambiguity is the diamond problem, and Java avoids it for classes, which carry state.
Multiple and hybrid inheritance are achieved with interfaces instead: a class can extend one class and implement many interfaces, as RoboTaxi does above. If two interfaces provide conflicting default methods, the class must override the method, as explained in Default Methods.
5. Constructors and super
Constructors are not inherited, but creating a subclass object always runs the parent constructors first, from the top of the hierarchy down:
public class ConstructorOrder {
static class A { A() { System.out.println("1. A constructor"); } }
static class B extends A { B() { System.out.println("2. B constructor"); } }
static class C extends B { C() { System.out.println("3. C constructor"); } }
public static void main(String[] args) {
new C(); // parent constructors always run first, top-down
}
}
1. A constructor 2. B constructor 3. C constructor
If a constructor does not call super(...) explicitly, the compiler inserts super(). If the parent has no no-argument constructor, the subclass must call one of its constructors explicitly. See super keyword and Constructor Chaining.
6. Controlling Inheritance
finalclass: cannot be extended (String,Integer).finalmethod: can be inherited but not overridden.sealedclass (Java 17): only the classes listed inpermitscan extend it.- Private constructor: prevents subclassing from outside the class.
7. Inheritance vs Composition
Inheritance couples the subclass tightly to the parent's implementation, and the subclass inherits everything, wanted or not. Use it only for a true IS-A relationship. For HAS-A relationships, use composition, holding another object as a field:
import java.util.ArrayList;
import java.util.List;
public class CompositionInstead {
// Inheritance misuse: a Stack IS-NOT-A ArrayList, but it would inherit add(index), remove(index)...
// Composition: a Stack HAS-A list and exposes only stack operations
static class Stack<T> {
private final List<T> items = new ArrayList<>();
void push(T item) { items.add(item); }
T pop() { return items.remove(items.size() - 1); }
T peek() { return items.get(items.size() - 1); }
boolean isEmpty() { return items.isEmpty(); }
}
public static void main(String[] args) {
Stack<String> pages = new Stack<>();
pages.push("home"); pages.push("java"); pages.push("inheritance");
System.out.println("Back from: " + pages.pop());
System.out.println("Now on: " + pages.peek());
}
}
Back from: inheritance Now on: java
Had Stack extended ArrayList, callers could insert or remove elements in the middle and break the stack. (The JDK's old java.util.Stack extends Vector has exactly this flaw.) See Aggregation for HAS-A relationships.
8. Advantages and Disadvantages
| Advantages | Disadvantages |
|---|---|
| Code reuse: common code lives in the parent | Tight coupling: parent changes can break subclasses |
| Enables method overriding and polymorphism | Deep hierarchies are hard to understand |
| Models natural IS-A hierarchies | Subclasses inherit members they may not want |
| Easier extension with new subclasses | Only one superclass per class |
9. Summary
- Inheritance lets a subclass reuse, override and extend a superclass using
extends. - Private members and constructors are not inherited; every class ultimately extends
Object. - Java supports single, multilevel and hierarchical inheritance of classes.
- Multiple and hybrid inheritance are achieved through interfaces.
- Parent constructors run first; prefer composition when the relationship is HAS-A.
Related Tutorials
Frequently Asked Questions (FAQ)
Q1. What is inheritance in Java?
A mechanism by which a class (subclass) acquires the fields and methods of another class (superclass) using extends, forming an IS-A relationship.
Q2. What are the types of inheritance in Java?
Single, multilevel and hierarchical inheritance with classes. Multiple and hybrid inheritance are possible only through interfaces.
Q3. Why doesn't Java support multiple inheritance of classes?
To avoid the diamond problem: ambiguity when two parent classes have members with the same name, and complexity around inherited state.
Q4. How is multiple inheritance achieved in Java?
By implementing multiple interfaces: class C extends A implements X, Y.
Q5. Are private members inherited?
They are part of the subclass object but not accessible from subclass code. They can be reached through inherited public or protected methods.
Q6. Are constructors inherited?
No. A subclass must define its own constructors, which call a parent constructor with super(...).
Q7. Which class is the superclass of all classes?
java.lang.Object. Every class directly or indirectly extends it.
Q8. What is the IS-A relationship?
The relationship created by inheritance: an object of the subclass is also an object of the superclass type, so it can be used wherever the superclass is expected.
Q9. What is the difference between IS-A and HAS-A?
IS-A is inheritance (a Car is a Vehicle). HAS-A is association, implemented by holding a reference (a Car has an Engine).
Q10. In what order do constructors run in inheritance?
From the top of the hierarchy down: Object, then each parent, then the subclass.
Q11. How can I prevent a class from being inherited?
Declare it final, make it sealed with a fixed list of subclasses, or give it only private constructors.
Q12. Can a subclass access protected members of the superclass?
Yes, even from a different package, through inheritance (via this or a reference of the subclass type).
Q13. Are static methods inherited?
They are accessible through the subclass name, but they belong to the parent and are hidden, not overridden, by same-named subclass static methods.
Q14. Can an interface extend a class?
No. An interface can only extend other interfaces.
Q15. What is hybrid inheritance?
A combination of two or more inheritance types. In Java it is achieved by combining class inheritance with interfaces.
Q16. What is cyclic inheritance?
A class extending itself directly or indirectly (A extends B, B extends A). Java forbids it with a compile error.
Q17. Why prefer composition over inheritance?
Composition is more flexible and less coupled: you expose only what you choose and can change the composed object without affecting a class hierarchy.
Q18. Can a subclass have more methods than its superclass?
Yes. Subclasses commonly add fields and methods; they can be called only through a reference of the subclass type.
Q19. Can a superclass reference call subclass-specific methods?
No. The reference type decides which methods can be called. Downcast (after an instanceof check) to call subclass-only methods.
Q20. Do records and enums support inheritance?
They cannot extend classes (records extend Record, enums extend Enum) and cannot be extended, but both can implement interfaces.