☕ Java

البرمجة كائنية التوجه: الوراثة في جافا: دليل مفصل

What is it and why? (a real-life analogy)

Imagine you decided to create your own video game. It will have different characters: a warrior, a mage, and an archer. Each of them has a name, health points, and the ability to attack. If we wrote code without inheritance, we would have to write the same fields (name, health) and methods (attack, take damage) again for each character class. This is time-consuming, tedious, and error-prone — what if we forget to update health in one class but not in another?

Now imagine there is a base template — "Character". It already contains everything common: name, health, attack method. The warrior, mage, and archer simply say: "I am a character, but I will add something of my own." The warrior will add "armor", the mage will add "magical energy", and the archer will add "shooting range". This is inheritance.

Inheritance is an OOP mechanism that allows you to create a new class based on an existing one. The new class (child, subclass, derived class) receives all the fields and methods of the parent class (superclass, base class) and can add its own or change (override) existing ones.

In real life, inheritance is found everywhere:

  • Cars: there is a base class "Vehicle" (has wheels, engine, steering wheel). "Passenger Car" (adds a trunk, 4 doors) and "Truck" (adds a cargo body, load capacity) inherit from it.
  • Animals: base class "Animal" (has a name, age, "make sound" method). "Cat" (meows), "Dog" (barks), "Cow" (moos) inherit from it.
  • Geometric shapes: base class "Shape" (has a color, "calculate area" method). "Circle", "Square", "Triangle" (each calculates area in its own way) inherit from it.

Why is this needed?

  1. Code reuse. No need to write the same thing many times.
  2. Hierarchy and logic. The code becomes structured, like a folder on a computer.
  3. Ease of changes. If you need to change something common (e.g., the health calculation method), you only change it in the parent class — and it updates for all descendants.
  4. Polymorphism. (We will study it later) — the ability to work with different classes through a single parent interface.

Theory: how it works internally

Let's look "under the hood" of Java and understand what happens in memory when we use inheritance.

Key concepts

  • Superclass (parent, base class) — the class from which others inherit. Contains common fields and methods.
  • Subclass (child, derived class) — the class that inherits. It automatically receives all public and protected fields and methods of the parent.
  • The extends keyword — it specifies that one class inherits from another.
  • Method Overriding — when a child provides a new implementation of a parent method. For example, the parent method "attack" deals 10 damage, but the warrior overrides it and deals 20.
  • The super keyword — a reference to the parent class. It can be used to call the parent's constructor or method.

What is inherited and what is not?

Class member Inherited? Note
public fields and methods Yes Directly accessible
protected fields and methods Yes Accessible in the child and within the same package
private fields and methods No They exist in the object but are not directly visible. Access via super or public methods of the parent
Constructors No The child must call the parent's constructor via super()
Static methods and fields Yes (with caveats) They belong to the class, not the object. The child can use them, but static methods cannot be overridden (this is called hiding)

How does Java build a child object?

When you create a child object (new Warrior()), Java does the following:

  1. Allocates memory for the object.
  2. Calls the parent class constructor (even if you didn't write one — the compiler inserts super() automatically).
  3. Initializes the parent's fields.
  4. Calls the child's constructor.
  5. Initializes the child's fields.

As a result, a single object resides in memory, containing all the fields of both the parent and the child. Some fields (private) are simply hidden from direct access.

Syntax in Java: all forms and variations

In Java, inheritance is implemented using the extends keyword. Unlike some languages (e.g., C++), Java supports only single class inheritance — one class can have only one direct parent. However, you can build chains: ClassC extends ClassB extends ClassA.

Basic form

// Parent class
class Animal {
    String name;
    int age;

    // Parent constructor
    public Animal(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public void makeSound() {
        System.out.println("The animal makes a sound");
    }
}

// Child class
class Dog extends Animal {
    String breed; // own field