allthingsare๐Ÿ…ฟ๏ธ.com Books โฌ…๏ธ Back allthingsare

โ€œThe only limit to our realization of tomorrow will be our doubts of today.โ€
[Franklin D. Roosevelt (1882โ€“1945) โ€“ 32nd President of the United States]


Extending Classes and Using super


12.1.1 What is Inheritance?

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.


12.1.2 How to Extend a Class in Java

In Java, you create inheritance relationships using the extends keyword.

Example: Letโ€™s start with a basic Animal class.

java
public class Animal { String name; void eat() { System.out.println(name + " is eating."); } }

This class has:

  • A field name

  • A method eat() that prints a simple message

Now, letโ€™s create a Dog class that extends Animal:

java
public class Dog extends Animal { void bark() { System.out.println(name + " says: Woof!"); } }

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.


12.1.3 Mini Lab: Basic Inheritance Example

Below is a full example showing inheritance in action.

java
public class Animal { String name; void eat() { System.out.println(name + " is eating."); } } public class Dog extends Animal { void bark() { System.out.println(name + " says: Woof!"); } public static void main(String[] args) { Dog d = new Dog(); d.name = "Buddy"; d.eat(); // Inherited from Animal d.bark(); // Defined in Dog } }

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.