← Back to Core Java Course | Chapter 8: Inheritance | Lesson 1 of 7

Java Inheritance Introduction

What is Inheritance?

Inheritance lets one class (the subclass) acquire the fields and methods of another (the superclass) using extends, so shared behavior only needs to be written once in the parent and is automatically available in every child class.

Example: What is Inheritance?

java
class Animal {
	void eat() {
		System.out.println("Eating");
	}
}
class Dog extends Animal {
}
public class Main {
	public static void main(String[] args) {
		new Dog().eat(); // inherited from Animal
	}
}

The super Keyword

The super keyword lets a subclass explicitly reach up to its immediate parent's fields, methods, or constructors — useful when the subclass needs to extend rather than fully replace the parent's behavior.

Example: The super Keyword

java
class Animal {
	String type = "Animal";
}
class Dog extends Animal {
	String type = "Dog";
	void show() {
		System.out.println(super.type); // reaches the parent's field
	}
}
public class Main {
	public static void main(String[] args) {
		new Dog().show();
	}
}

Method Overriding

Overriding happens when a subclass redefines a method it inherited from its parent, giving that method a new implementation specific to the subclass while keeping the same method signature the parent declared.

Example: Method Overriding

java
class Animal {
	void sound() {
		System.out.println("Some sound");
	}
}
class Dog extends Animal {
	@Override
	void sound() {
		System.out.println("Bark");
	}
}
public class Main {
	public static void main(String[] args) {
		new Dog().sound();
	}
}

IS-A Relationship

Inheritance is meant to model a genuine "is-a" relationship — a Dog really is an Animal, a Sedan really is a Vehicle — and reaching for inheritance in cases that don't fit this pattern usually leads to awkward, hard-to-maintain class hierarchies.

Example: IS-A Relationship

java
class Vehicle {}
class Sedan extends Vehicle {} // a Sedan IS-A Vehicle
public class Main {
	public static void main(String[] args) {
		Vehicle v = new Sedan();
		System.out.println(v instanceof Vehicle);
	}
}

Constructor Call Sequence

When a subclass object is constructed, the parent class's constructor always runs first (implicitly, or explicitly via super(...)), and only after that completes does the subclass's own constructor body execute.

Example: Constructor Call Sequence

java
class Animal {
	Animal() {
		System.out.println("Animal constructor");
	}
}
class Dog extends Animal {
	Dog() {
		System.out.println("Dog constructor");
	}
}
public class Main {
	public static void main(String[] args) {
		new Dog(); // Animal constructor runs first
	}
}

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.