Java Inheritance Introduction
In this page:
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?
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
}
}
Login to try C/C++/Java/PHP code in the editor
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
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();
}
}
Login to try C/C++/Java/PHP code in the editor
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
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();
}
}
Login to try C/C++/Java/PHP code in the editor
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
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);
}
}
Login to try C/C++/Java/PHP code in the editor
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
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 try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: