Java Inheritance
extends Keyword
Inheritance allows a child class (subclass) to acquire the fields and methods of a parent class (superclass) using the extends keyword. Java supports single inheritance — a class can extend only one class, but can implement multiple interfaces.
// Parent class (superclass)
class Animal {
String name;
int age;
public Animal(String name, int age) {
this.name = name;
this.age = age;
}
public void eat() {
System.out.println(name + " is eating.");
}
public void sleep() {
System.out.println(name + " is sleeping.");
}
}
// Child class (subclass) — inherits Animal
class Dog extends Animal {
String breed;
public Dog(String name, int age, String breed) {
super(name, age); // calls Animal's constructor
this.breed = breed;
}
public void bark() {
System.out.println(name + " says: Woof!");
}
// Method overriding — redefine parent behavior
@Override
public void eat() {
super.eat(); // call parent version first
System.out.println(name + " wags its tail while eating.");
}
}
public class Inheritance {
public static void main(String[] args) {
Dog dog = new Dog("Rex", 3, "Labrador");
dog.eat(); // overridden version
dog.sleep(); // inherited from Animal
dog.bark(); // Dog-specific method
System.out.println(dog.breed); // Labrador
}
}
Method Overriding & @Override
A subclass can provide its own implementation of a method defined in the parent class. Rules for overriding:
final Class and final Method
class Vehicle {
// final method — cannot be overridden by subclasses
public final void startEngine() {
System.out.println("Engine started.");
}
public void accelerate() {
System.out.println("Vehicle accelerating.");
}
}
class Truck extends Vehicle {
@Override
public void accelerate() {
System.out.println("Truck accelerating slowly.");
}
// Cannot override startEngine() — it's final
}
// final class — cannot be extended
final class ImmutablePoint {
final int x;
final int y;
public ImmutablePoint(int x, int y) {
this.x = x;
this.y = y;
}
}
// class SubPoint extends ImmutablePoint {} // ERROR: cannot extend final class
public class FinalDemo {
public static void main(String[] args) {
Truck t = new Truck();
t.startEngine(); // Engine started.
t.accelerate(); // Truck accelerating slowly.
ImmutablePoint p = new ImmutablePoint(3, 4);
System.out.println("Point: (" + p.x + ", " + p.y + ")");
}
}
Ready to Level Up Your Skills?
Explore 500+ free tutorials across 20+ languages and frameworks.