DEV Community

Programming Entry Level: for beginners inheritance

Understanding Inheritance for Beginners

Have you ever noticed how you might share traits with your parents? Maybe you have the same eye color, or a similar sense of humor. In programming, “inheritance” is a similar idea! It’s a powerful concept that lets you create new building blocks (called classes) based on existing ones, reusing code and making your programs more organized. Understanding inheritance is a key skill for any programmer, and it often comes up in technical interviews. This post will break down inheritance in a way that’s easy to grasp, even if you’re just starting out.

Understanding Inheritance

Imagine you're building a game with different types of vehicles. You might have cars, trucks, and motorcycles. All of these are vehicles – they all have wheels, engines, and can move. Instead of writing the code for wheels, engines, and movement separately for each type of vehicle, we can create a general “Vehicle” class and then build cars, trucks, and motorcycles based on that Vehicle class.

That’s inheritance in a nutshell! A class “inherits” properties and behaviors from another class.

  • The original class is called the parent class or superclass.
  • The new class is called the child class or subclass.

The child class automatically gets everything the parent class has, and then you can add new features or modify existing ones to make it unique. This avoids repeating code and makes your program easier to maintain.

Here's a simple visual representation using a mermaid diagram:

classDiagram
    Vehicle <|-- Car : inherits
    Vehicle <|-- Truck : inherits
    Vehicle <|-- Motorcycle : inherits

    class Vehicle{
        +hasWheels()
        +hasEngine()
        +move()
    }
    class Car{
        +numberOfDoors()
    }
    class Truck{
        +loadCapacity()
    }
    class Motorcycle{
        +hasSidecar()
    }
Enter fullscreen mode Exit fullscreen mode

This diagram shows that Car, Truck, and Motorcycle all inherit from Vehicle. They all have the properties and methods of Vehicle, but they also have their own unique characteristics.

Basic Code Example

Let's see how this looks in code. We'll use Python for this example, but the concept applies to many programming languages.

class Animal:
    def __init__(self, name):
        self.name = name

    def speak(self):
        print("Generic animal sound")

Enter fullscreen mode Exit fullscreen mode

Now let's explain this code:

  1. class Animal: creates a new class named Animal. This is our parent class.
  2. def __init__(self, name): is a special method called the constructor. It's called when you create a new Animal object. It takes the name as input and stores it in the self.name variable. self refers to the instance of the class.
  3. self.name = name assigns the given name to the name attribute of the animal.
  4. def speak(self): defines a method called speak. This method prints a generic animal sound.

Now, let's create a child class called Dog that inherits from Animal:

class Dog(Animal):
    def __init__(self, name, breed):
        super().__init__(name) # Call the parent class's constructor

        self.breed = breed

    def speak(self):
        print("Woof!")

Enter fullscreen mode Exit fullscreen mode

Let's break down the Dog class:

  1. class Dog(Animal): This line is crucial! It tells Python that Dog inherits from Animal.
  2. def __init__(self, name, breed): The constructor for Dog takes both a name and a breed.
  3. super().__init__(name): This is how we call the constructor of the parent class (Animal). We're passing the name to the Animal constructor to initialize the name attribute. super() is a way to access the parent class.
  4. self.breed = breed: This line adds a new attribute specific to Dog – the breed.
  5. def speak(self): This method overrides the speak method from the Animal class. This means that when you call speak on a Dog object, it will print "Woof!" instead of "Generic animal sound".

Finally, let's create some objects and test it out:

animal = Animal("Generic Animal")
animal.speak()  # Output: Generic animal sound

dog = Dog("Buddy", "Golden Retriever")
dog.speak()  # Output: Woof!

print(dog.name) # Output: Buddy

print(dog.breed) # Output: Golden Retriever

Enter fullscreen mode Exit fullscreen mode

Common Mistakes or Misunderstandings

Here are some common pitfalls when learning inheritance:

❌ Incorrect code:

class Dog(Animal):
    def __init__(self, breed):
        self.breed = breed
Enter fullscreen mode Exit fullscreen mode

✅ Corrected code:

class Dog(Animal):
    def __init__(self, name, breed):
        super().__init__(name)
        self.breed = breed
Enter fullscreen mode Exit fullscreen mode

Explanation: Forgetting to call the parent class's constructor (super().__init__(name)) means the name attribute won't be initialized. You need to initialize the attributes inherited from the parent class.

❌ Incorrect code:

def speak():
    print("Woof!")
Enter fullscreen mode Exit fullscreen mode

✅ Corrected code:

def speak(self):
    print("Woof!")
Enter fullscreen mode Exit fullscreen mode

Explanation: Methods in a class need to take self as the first argument. self refers to the instance of the class.

❌ Incorrect code:

class Cat(Animal):
    def speak():
        print("Meow!")
Enter fullscreen mode Exit fullscreen mode

✅ Corrected code:

class Cat(Animal):
    def speak(self):
        print("Meow!")
Enter fullscreen mode Exit fullscreen mode

Explanation: Similar to the previous mistake, forgetting self in the method definition will cause errors.

Real-World Use Case

Let's imagine you're building a simple game with different types of characters. You could have a base Character class with attributes like name, health, and attack_power. Then, you could create subclasses like Warrior, Mage, and Archer, each inheriting from Character and adding their own unique abilities.

class Character:
    def __init__(self, name, health, attack_power):
        self.name = name
        self.health = health
        self.attack_power = attack_power

    def attack(self):
        print(f"{self.name} attacks with power {self.attack_power}!")

class Warrior(Character):
    def __init__(self, name):
        super().__init__(name, 150, 20) # Warriors have more health and attack

        self.armor = 10

    def defend(self):
        print(f"{self.name} raises their shield!")

warrior = Warrior("Arthur")
warrior.attack()
warrior.defend()
print(warrior.health)
Enter fullscreen mode Exit fullscreen mode

This demonstrates how inheritance can help you create a structured and reusable codebase.

Practice Ideas

Here are a few exercises to help you solidify your understanding of inheritance:

  1. Shape Hierarchy: Create a Shape class with a calculate_area method. Then, create subclasses like Circle, Rectangle, and Triangle that override the calculate_area method to calculate the area of each shape.
  2. Vehicle Simulator: Expand on the vehicle example from earlier. Add more attributes (like color, model) and methods (like honk, accelerate).
  3. Animal Sounds: Create an Animal class and several subclasses (e.g., Dog, Cat, Cow) that each have their own speak method.
  4. Employee Management: Create an Employee class with attributes like name and salary. Then, create subclasses like Manager and Developer with additional attributes and methods.
  5. Simple Inventory System: Create a Item class with attributes like name and value. Then create subclasses like Weapon, Potion, and Armor with specific properties for each item type.

Summary

Congratulations! You've taken your first steps into the world of inheritance. You've learned that inheritance allows you to create new classes based on existing ones, reusing code and making your programs more organized. Remember the key concepts: parent class, child class, super(), and method overriding.

Don't be afraid to experiment and practice. The more you use inheritance, the more comfortable you'll become with it. Next, you might want to explore more advanced concepts like multiple inheritance and abstract classes. Keep coding, and have fun!

Top comments (0)