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. finalmethods cannot be overridden;finalclasses 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?