Computer Engineering is coming soon

We're still writing and reviewing the notes for every subject, and we'll open it when every subject is ready. Meanwhile you can practise aptitude, ask Aria about any subject, or see the branches that are ready.

Inheritance in Java

Clear, exam-focused notes on Java inheritance: what it is, rules, syntax, examples (runnable Java), common mistakes and likely exam questions.

Drafted with Aria, reviewed by the AiCanCode.org team · Updated . How we write and check our notes. Spotted an error? Use Give Feedback at the bottom of the page.

Why it matters

Inheritance is a core object-oriented mechanism to build new classes from existing ones, letting engineers reuse code, express an "is-a" relationship and enable polymorphic behaviour. In Java you use inheritance to design class hierarchies, implement frameworks (using abstract classes and interfaces), and to allow runtime method selection (dynamic binding) that makes APIs extensible and testable.

Key ideas

Start with these definitions (every term is defined before use):

  • Class: a blueprint for objects; defines fields (state) and methods (behaviour).
  • Object: a runtime instance of a class.
  • Inheritance: a relation where a subclass (also called derived class or child) acquires fields and methods from a superclass (also base class or parent). In Java this is written with extends for classes.
    • Exact definition: A class B inherits from class A if B declares class B extends A. This means B obtains the accessible members of A (subject to access rules), and an object of B may be treated as an A (B is-a A).
  • Is-a relationship: semantic statement used to justify inheritance: if every instance of B can validly be used where an A is required, then B is-a A.

Rules and exact statements universities ask for:

  1. Single-class inheritance: Java supports single inheritance for classes. Exact statement: "A class may extend at most one other class." (Assumption: applies to classes, not interfaces.)

  2. Interfaces: A class may implement any number of interfaces. Interfaces may extend multiple interfaces.

  3. Constructors are not inherited. Exact statement: "Subclasses do not inherit constructors from their superclass; they may call superclass constructors using super(...)." Explain: the subclass must chain to a superclass constructor explicitly using super(...) or implicitly; if no explicit constructor invocation (super(...) or this(...)) is the first statement, the compiler inserts a call to the no-argument superclass constructor (super()), and compilation fails if that constructor does not exist.

  4. Member inheritance and access rules (exact, subject to access modifiers):

    • private members of the superclass are not inherited by subclasses and are accessible only within the declaring class.
    • protected members are accessible to all classes in the same package, and to subclasses even across packages; in a different package, access is permitted only from within the subclass and only via a reference whose compile-time type is the subclass (or its subtype), not via an arbitrary superclass reference.
    • public members are accessible everywhere.
    • package-private (no modifier) members are accessible only to classes in the same package.
  5. Overriding vs overloading (exact definitions):

    • Method overriding: A subclass provides a method with the same signature (name and parameter types) as a non-static method in its superclass, and the subclass method is invoked on a subclass object at runtime. Overriding requires compatible return type and cannot reduce visibility. Final methods cannot be overridden. For checked exceptions, an overriding method may not declare new or broader checked exceptions than the overridden method; it may declare fewer or narrower checked exceptions (unchecked exceptions are not restricted).
    • Method overloading: Multiple methods in the same class (or inherited plus new) have the same name but different parameter lists; selection is at compile-time based on parameter types. The return type alone does not distinguish overloaded methods (it is not part of the method signature for overloading).
  6. Dynamic binding (runtime polymorphism): Exact statement: "When a non-static method is invoked on a reference whose compile-time type is a class or interface, the JVM dispatches to the implementation determined by the runtime class of the object (most specific override), not by the compile-time type." This is why overriding supports polymorphism.

  7. super keyword: used to (a) call superclass constructors (super(...)) and (b) access superclass members (super.method(...) or super.field).super() must be the first statement in a constructor when used.

  8. final keyword: When applied to a class it prevents extension (final class C {}); applied to a method it prevents overriding; applied to a field it prevents reassignment.

  9. abstract classes and methods: An abstract class may have abstract methods (declared but not implemented). Exact statement: "If a class contains one or more abstract methods, the class must be declared abstract. A concrete subclass must implement all inherited abstract methods, or itself be declared abstract." A class may be declared abstract even if it has no abstract methods.

  10. Interfaces and default methods: Interfaces declare method signatures. Since Java 8 an interface may provide a default method implementation. If a class inherits a method with the same signature from a class and an interface default, the class (or superclass) implementation wins. If two interfaces provide conflicting default methods, the implementing class must override.

  11. Object class: Exact statement: "All classes implicitly extend java.lang.Object if no explicit superclass is given. Therefore every class inherits methods like toString(), equals(Object), and hashCode()." (These can be overridden.)

  12. Covariant return types: Java allows an overriding method to return a subtype of the return type declared in the overridden method.

  13. Type casting & instanceof:

  • Upcasting: assigning a subclass object to a superclass reference; safe and implicit.
  • Downcasting: casting a superclass reference to a subclass type; requires explicit cast and may throw ClassCastException at runtime if incorrect.
  • instanceof checks if an object is compatible with a given type at runtime.
  1. Liskov Substitution Principle (LSP) — exact statement used in design: "Objects of a subtype should be replaceable with objects of the supertype without altering the desirable properties of a program (correctness, task performed)." This is a design guideline for correct overriding and behavioural subtyping.

Diagram to draw (for exam answers): draw two rectangles stacked vertically or side-by-side. Top rectangle: label class Parent and list one method void m() inside. Below (or to the right) draw class Child extends Parent and list void m() (override) and void newMethod(). Draw an arrow from Child to Parent and label arrow extends. If showing dynamic binding, add a runtime object bubble new Child() and a reference Parent p = new Child(); p.m() with an arrow from p to the object; note that Child.m() executes.

Formulas

class Sub extends Super { ... } — Subclass declaration

class C implements I1, I2 { ... } — class implementing interfaces

public Sub(...) { super(...); ... } — calling superclass constructor

@Override returnType methodName(params) { ... } — method overriding annotation and signature

final class C {} — class cannot be extended

abstract class C { abstract void f(); } — abstract class and abstract method

interface I { default void d() { ... } } — default method in interface

Super s = new Sub(); — upcasting (implicit)

Sub t = (Sub) s; — downcasting (explicit)

if (obj instanceof Sub) { ... } — runtime type check

super.method(args); — call superclass method

Note: static methods are not overridden; they are hidden. Fields are also hidden (not overridden); field access is resolved at compile time based on the reference type, not the runtime type. Use @Override only for instance methods.

Worked examples

Example 1 — Constructor chaining, fields, and super():

// File: PersonEmployeeDemo.java public class PersonEmployeeDemo { static class Person { protected String name; public Person(String name) { this.name = name; System.out.println("Person constructed: " + name); } public String getName() { return name; } }

static class Employee extends Person {
    private int id;
    public Employee(String name, int id) {
        super(name); // calls Person(String)
        this.id = id;
        System.out.println("Employee constructed: id=" + id);
    }
    public int getId() { return id; }
}

public static void main(String[] args) {
    Employee e = new Employee("Asha", 101);
    System.out.println(e.getName() + " " + e.getId());
}

}

Sample output (exact): Person constructed: Asha Employee constructed: id=101 Asha 101

Example 2 — Method overriding and dynamic binding:

// File: ShapeDemo.java public class ShapeDemo { static class Shape { public String name() { return "shape"; } public String draw() { return "Drawing " + name(); } } static class Circle extends Shape { @Override public String name() { return "circle"; } } public static void main(String[] args) { Shape s = new Circle(); // upcast System.out.println(s.draw()); } }

Sample output (exact): Drawing circle

Explain: draw() is defined in Shape and calls name(); at runtime the overriding Circle.name() is used.

Example 3 — Interfaces, default methods and conflict resolution:

// File: DefaultMethodDemo.java public class DefaultMethodDemo { interface I1 { default String msg() { return "I1"; } } interface I2 { default String msg() { return "I2"; } } static class C implements I1, I2 { // required: resolve conflict @Override public String msg() { // can delegate to a chosen interface return I1.super.msg() + ": overridden in C"; } } public static void main(String[] args) { C c = new C(); System.out.println(c.msg()); } }

Sample output (exact): I1: overridden in C

Note: if class C extended a concrete class that also provided msg(), that class's msg() would win over interface defaults.

Common mistakes

  • Saying constructors are inherited. They are not; subclasses must call superclass constructors.
  • Thinking private members are inherited and directly accessible — they are not accessible in subclass code.
  • Expecting static methods to be overridden. They are hidden; runtime dispatch does not apply.
  • Forgetting to use @Override (helps catch signature mistakes) or thinking @Override is mandatory.
  • Downcasting without instanceof check and not handling possible ClassCastException.
  • Believing Java supports multiple class inheritance — Java does not for classes (interfaces are different).
  • Ignoring access modifiers: assuming protected always allows access across packages. Correct rule: protected is accessible to all classes in the same package; in a different package it is accessible only within subclasses, and only via a reference whose compile-time type is the subclass (or its subtype).

For your exam

Kinds of questions:

  • Definitions: define inheritance, subclass, superclass, overriding, overloading, polymorphism.
  • Short notes: constructor chaining, super, final, abstract, interfaces, default methods, Object as root.
  • Derivations / explanations: show how dynamic binding works with example and draw object/reference diagram.
  • Programs: small Java programs that demonstrate overriding, constructor order, casting and instanceof.
  • Diagrams: class hierarchy diagrams showing extends arrows and overridden methods.

What a full-marks answer includes:

  • Precise definitions, correct keywords and syntax, access rule details and constraints (e.g., final, abstract), and a small tested code snippet or clear diagram. If asked to reason about runtime output, show both compile-time type and runtime type and explain which method body runs and why.

Quick check

  1. What keyword does a Java class use to inherit from another class?
  2. Will a subclass inherit private methods so it can call them directly? (Yes/No)
  3. If Super s = new Sub(); s.m(); and m() is overridden in Sub, which implementation runs?

Answers: extends; No; the Sub implementation (runtime override).

Finished this topic? Mark it so your progress, study plan and readiness keep up.

Stuck on something here?