Inheritance & Polymorphism
Inheritance — Don't Start from Scratch
Imagine you've built a great Vehicle class. Now you need a Car, a Truck, and a Motorcycle. They all have engines, speeds, and can move — but each adds its own twist. Do you rewrite all that shared code three times? Nope!
Inheritance lets a new class (the child or subclass) automatically get all the fields and methods of an existing class (the parent or superclass). The child can then add its own stuff or change how inherited methods work.
In Java, you use the extends keyword. A child class can only extend one parent (single inheritance).
Basic Inheritance with extends
Method Overriding & Polymorphism
Overriding means a child class provides its own version of a method it inherited. The parent has a speak() method that says "...", but the Dog overrides it to say "Woof!" and the Cat overrides it to say "Meow!"
Polymorphism is the magic that happens when you use a parent type to hold a child object. You'll see this pattern everywhere in data structures — for example, different node types in a binary search tree. You can call speak() on an Animal variable, and Java automatically picks the right version based on what the object actually is. It's like calling "perform!" to a group of musicians — each one plays their own instrument.
Use the @Override annotation to tell Java (and other developers) that you're intentionally replacing a parent method. It also catches typos — if you misspell the method name, the compiler will warn you.