Inheritance
Inheritance lets one class reuse the fields and methods of another, using the
extends keyword. The class doing the reusing is the subclass (or child class);
the class being reused is the superclass (or parent class).
The extends Keyword
A subclass automatically gets every non-private field and method from its superclass, and can add its own on top.
public class Animal {
void speak() {
System.out.println("Some generic animal sound");
}
}
public class Dog extends Animal {
// Dog inherits speak() automatically - and can add its own members
}
Overriding a Method
A subclass can provide its own version of an inherited method — this is called
overriding. The overriding method must have the exact same name, parameter list, and
return type as the one in the superclass. Always mark it with @Override; it's not required by
the compiler, but it catches mistakes (like typos) by verifying you're actually overriding something.
public class Dog extends Animal {
@Override
void speak() {
System.out.println("Woof!");
}
}
public class Cat extends Animal {
@Override
void speak() {
System.out.println("Meow!");
}
}
Dog d = new Dog();
Cat c = new Cat();
d.speak(); // Woof!
c.speak(); // Meow!
@Override above a method that doesn't actually match the superclass's method signature causes a compile error — a great safety net.Calling the Parent with super
Sometimes you want to extend the parent's behavior rather than fully replace it. The super keyword lets an overriding method call the superclass's original version.
public class Dog extends Animal {
@Override
void speak() {
super.speak(); // runs Animal's version first
System.out.println("Woof!");
}
}
super() (with parentheses) has a related but different job: calling the parent's constructor from inside a child's constructor, so the parent gets a chance to set up its own fields first.
public class Animal {
String name;
Animal(String name) {
this.name = name;
}
}
public class Dog extends Animal {
Dog(String name) {
super(name); // must run Animal's constructor to set "name"
}
}
Single Inheritance in Java
A Java class can only extends one superclass — Java doesn't allow a class to
inherit from multiple classes at once. This keeps class hierarchies simple and avoids ambiguity about which
parent's version of a method should apply.