Extending Classes and Using super
Inheritance is one of the four fundamental pillars of object-oriented programming (OOP).
In simple terms, inheritance allows you to create a new class (child class) that reuses the fields and methods of an existing class (parent class).
The child class inherits everything from the parent and can extend or customize the behavior as needed.
Why is inheritance so important?
Code reuse: You donโt repeat the same fields and logic in multiple classes โ you write it once in the parent.
Hierarchical structure: You can design a clear class hierarchy based on shared traits.
Easy maintenance: If you improve the parent, all children benefit automatically.
A well-designed inheritance chain keeps code DRY (Donโt Repeat Yourself) and models real-world relationships.
In Java, you create inheritance relationships using the extends
keyword.
Example: Letโs start with a basic Animal
class.
This class has:
A field name
A method eat()
that prints a simple message
Now, letโs create a Dog
class that extends Animal
:
Key points:
The Dog
class inherits name
and eat()
from Animal
.
Dog
adds its own method bark()
.
So with no extra work, Dog
automatically has everything Animal
has.
Below is a full example showing inheritance in action.
When you run this:
d
is a Dog
object that inherits the name
field and eat()
method from Animal
.
bark()
is unique to Dog
.
This shows how inheritance lets you reuse code while still letting you extend the child class with specialized behavior.