How inheritance works
Extend a class
The child class inherits accessible members from its parent.
class Animal {
void speak() {
System.out.println("A sound");
}
}
class Dog extends Animal {
}
Override behavior
An override supplies child-specific behavior. @Override lets the compiler verify the intended relationship.
class Dog extends Animal {
@Override
void speak() {
System.out.println("Woof");
}
}
Use polymorphism
A parent-typed variable can refer to a child object; overridden instance methods still use the child's implementation.
Animal animal = new Dog();
animal.speak(); // Woof
Use inheritance carefully
Use inheritance for a genuine “is-a” relationship. Prefer composition when one object merely uses or contains another.