🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
💼 Servicesℹ️ About✉️ ContactView Pricing Plansfrom $10

Java Inheritance — extends, super, Method Overriding

Java BasicsInheritance🟢 Free Lesson

Java Inheritance — extends, super, Method Overriding

Learning Objectives

  • Create subclasses with the extends keyword
  • Call superclass constructors using super
  • Override superclass methods in a subclass
  • Describe single inheritance and the Object root class

Overview

Inheritance lets one class build on another. The existing class is called the superclass or parent, and the new class is called the subclass or child. The subclass inherits fields and methods, so you avoid duplication and express a clear is-a relationship.

A classic example is that a checking account is a type of account. Account already models balance and deposit; CheckingAccount adds an overdraft rule without rewriting the shared code. Java supports single inheritance: a class may extend exactly one superclass, which keeps hierarchies easy to follow.

Using extends

The extends keyword establishes the relationship. The subclass immediately gains access to non-private members of the superclass.

class Animal {
    String name;

    void speak() {
        System.out.println(name + " makes a sound");
    }
}

class Dog extends Animal {
    void fetch() {
        System.out.println(name + " fetches the ball");
    }
}

public class InheritDemo {
    public static void main(String[] args) {
        Dog d = new Dog();
        d.name = "Rex";
        d.speak();
        d.fetch();
    }
}

Dog declares fetch itself and inherits speak and name from Animal. One object type therefore combines behavior from both classes.

Constructors and super

Constructors are not inherited, because each class may need different setup. When you create a subclass object, its constructor runs, and the superclass constructor runs first to initialize inherited state. The keyword super with parentheses in parentheses performs that superclass call.

class Animal {
    String name;

    Animal(String name) {
        this.name = name;
        System.out.println("Animal created");
    }
}

class Dog extends Animal {
    int tricks;

    Dog(String name, int tricks) {
        super(name);
        this.tricks = tricks;
        System.out.println("Dog created");
    }
}

If a superclass has only a parameterized constructor, the subclass must call it explicitly. If the superclass has a no-argument constructor, Java inserts super with empty parentheses automatically when you omit it.

Method Overriding

When a subclass provides its own implementation of a method the superclass already defines, that is method overriding. The signature must match: same name, same parameter types, and a return type that is the same or a covariant subtype. The access level may not shrink.

class Shape {
    double area() {
        return 0.0;
    }
}

class Circle extends Shape {
    double radius;

    Circle(double radius) {
        this.radius = radius;
    }

    @Override
    double area() {
        return 3.14159 * radius * radius;
    }
}

The @Override annotation is optional but valuable. If the signature does not truly match, the compiler complains and catches what would otherwise be a silent bug where a new method appears instead of a replacement.

Overloading Versus Overriding

Overloading means the same class offers multiple methods with different parameter lists and is resolved at compile time. Overriding means a subclass redefines an inherited method with the same signature and is resolved at runtime based on the actual object. Confusing the two is common, so keep the definitions separate in your notes.

Protected and Package Access

Superclass members marked protected remain visible to subclasses even across packages, while staying hidden from unrelated classes. Package private members are visible only inside the same package. Private members are never visible to subclasses, which is the right choice when data must stay inside the class that owns it.

The Object Class

Every class ultimately extends java.lang.Object. If you write class Robot with no extends clause, Robot still inherits methods such as toString, equals, and hashCode from Object. Overriding toString is a popular early customization because it controls how print statements display your objects.

Design Guidelines

Favor shallow hierarchies. Deep chains such as A extends B extends C extends D make behavior hard to trace. Prefer composition, meaning using other objects as fields, when the relationship is not truly an is-a link. A car has an engine; a car is not an engine.

Key Takeaways

💡

  • extends creates a subclass that inherits accessible superclass members
  • Constructors are not inherited; super runs the superclass constructor first
  • Overriding replaces an inherited implementation when the signature matches
  • @Override helps the compiler verify your intent
  • Java has single inheritance, and every class ultimately extends Object

Practice Questions

  1. Create a Vehicle superclass with a start method and a Car subclass that overrides it, then call both versions.
  2. Why must a parameterized-only superclass constructor be called with super from a subclass?
  3. State one situation where composition is a better design choice than inheritance.

Extended Learning: Beyond the Basics

Key Concepts Summary

This lesson covers fundamental concepts that serve as building blocks for more advanced topics. Master these basics before moving to intermediate and advanced material.

Prerequisite Knowledge

Before studying this topic in depth, ensure you understand:

  • Basic definitions and terminology
  • Core formulas and their derivations
  • Common applications in real-world scenarios
  • Typical pitfalls and misconceptions

Step-by-Step Walkthrough

Let us work through a complete example to solidify understanding:

Step 1: Identify the problem type. Determine which category this problem falls into and which approach is most appropriate.

Step 2: Apply the relevant formula. Substitute known values into the appropriate equation, paying attention to units and constraints.

Step 3: Simplify and solve. Work through the algebra step by step, checking each intermediate result.

Step 4: Verify the answer. Check that the solution satisfies the original conditions and makes logical sense.

Common Mistakes to Avoid

  1. Misidentifying the problem type — Always start by categorizing the problem
  2. Incorrect formula application — Verify the formula applies to your specific case
  3. Unit errors — Always check units are consistent throughout
  4. Sign errors — Pay careful attention to positive and negative values
  5. Rounding too early — Keep full precision until the final answer
  6. Forgetting constraints — Check that solutions satisfy all given conditions

Real-World Applications

Understanding this concept is essential for:

  • Advanced problem solving in examinations
  • Building intuition for more complex topics
  • Developing analytical thinking skills
  • Applying mathematical reasoning to practical situations

Practice Exercises

  1. Basic: Solve 5 problems of increasing difficulty using the core concept.
  2. Intermediate: Apply the concept to word problems with multiple steps.
  3. Advanced: Combine this concept with 2-3 other topics in a comprehensive problem.
  4. Challenge: Create your own problem that requires this concept plus additional knowledge.

Interview and Exam Tips

  • Common question patterns: Identify which exam or interview formats test this topic
  • Time management: Practice completing problems within time constraints
  • Common traps: Know the typical mistakes examiners set as distractors
  • Verification strategy: Develop a quick method to check your answer

Related Topics

Quick Reference Card

ConceptFormula/RuleKey InsightCommon Use
Core DefinitionSee main textUnderstand the intuitionFoundation for all applications
Key FormulaSee main textMemorize the derivationDirect problem solving
Special CaseSee main textRecognize when it appliesSimplifies complex problems
Edge CaseSee main textKnow the limitationsAvoids errors

Further Reading

For students who want to go deeper:

  • Standard textbooks on the subject
  • Research papers applying this concept
  • Online courses with video explanations
  • Practice problem collections with detailed solutions
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-11-14

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert Java Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement