Inheritance
Inheritance
Inheritance lets you create a new class based on an existing one. The new class (subclass or child) gets the fields and methods of the existing class (superclass or parent) and can add or change behavior. This is one of the pillars of object-oriented programming.
extends keyword
A class inherits from another using extends. The subclass automatically has all non-private members of the superclass.
javapublic class Animal { protected String name; public Animal(String name) { this.name = name; } public void speak() { System.out.println(name + \" makes a sound\"); } } public class Dog extends Animal { public Dog(String name) { super(name); // call parent constructor } @Override public void speak() { System.out.println(name + \" barks\"); } }
Dog extends AnimalmeansDogis a subclass ofAnimal. EveryDogis anAnimal.super(name)must be the first statement in the constructor if you use it; it calls the parent constructor.protectedallows the field to be visible in subclasses (unlikeprivate).@Overridemarks that this method replaces the parent implementation. Not required but good practice.
Using the hierarchy
A variable of the superclass type can hold a subclass instance (polymorphism):
javaAnimal a = new Dog(\"Rex\"); a.speak(); // Rex barks
The JVM calls the actual object type method: Dog.speak, not Animal.speak. That is runtime polymorphism.
Object as root
In Java every class ultimately extends Object. So all classes have methods like toString(), equals(), and hashCode(). Override them when you need meaningful behavior (e.g. comparing two objects by their fields).