JV

Java Fundamentals

19 lessons

Progress0%
1. Introduction to Java
1What is Java?
2. Variables and Data Types
1Primitive Types
3. Control Flow
ConditionalsLoops
4. Methods
Defining MethodsMethod Overloading
5. Object-Oriented Programming
Classes and ObjectsInheritanceInterfaces and Abstract Classes
6. Collections
ArrayList and LinkedListHashMap and HashSet
7. Exception Handling
Checked & Unchecked Exceptionstry-with-resources & Custom Exceptions
8. Generics
Generic Classes & MethodsWildcards & Type Erasure
9. Modern Java
Lambdas & Functional InterfacesStream API & Optional
10. File I/O
java.nio.file APIBuffered I/O & try-with-resources
All Tutorials
JavaObject-Oriented Programming
Lesson 8 of 19 min
Chapter 5 · Lesson 2

Inheritance

Inheritance in Java

Inheritance allows a class to acquire the fields and methods of another class, promoting code reuse.

extends A subclass inherits all non-private members of its superclass:

java
class Dog extends Animal { … }

super

  • super(args) — calls the superclass constructor (must be first line).
  • super.method() — calls the superclass version of an overridden method.

Method overriding A subclass provides its own implementation of a method inherited from the parent. The signature must match exactly.

@Override annotation Tells the compiler you intend to override. If the method doesn't exist in the parent, the compiler reports an error — catching typos.

Key points:

  • Java supports single inheritance (one parent class).
  • All classes implicitly extend Object.
  • final methods cannot be overridden; final classes cannot be extended.

Code Examples

extends, super, and @Overridejava
public class Animal {
    protected String name;

    public Animal(String name) {
        this.name = name;
    }

    public String sound() {
        return "...";
    }

    public String describe() {
        return name + " says " + sound();
    }
}

class Cat extends Animal {
    private boolean indoor;

    public Cat(String name, boolean indoor) {
        super(name);
        this.indoor = indoor;
    }

    @Override
    public String sound() { return "Meow"; }

    public static void main(String[] args) {
        Cat c = new Cat("Whiskers", true);
        System.out.println(c.describe());
        System.out.println("Indoor: " + c.indoor);
    }
}

super(name) passes the name to Animal's constructor. @Override ensures sound() actually exists in the parent.

Quick Quiz

1. What does `@Override` do?

2. How many classes can a Java class directly extend?

Was this lesson helpful?

PreviousNext