DEV Community

Cover image for Understanding Java Inheritance: A Friendly Guide 🌳
Kudzai Murimi
Kudzai Murimi

Posted on

Understanding Java Inheritance: A Friendly Guide 🌳

Hey there, fellow developers! πŸ‘‹ In our Java learning journey, we last explored Encapsulation (check it out here: Understanding Encapsulation in Java).

Today, let’s dive into Inheritance in Java, and I promise to make it as simple as possible. Think of inheritance like a family treeβ€”where children inherit traits from their parents. Well, in Java, it's pretty much the same! Let's break it down in an easy-to-understand way.

What is Inheritance? πŸ€”

Imagine you're making a video game. You have different characters: warriors, mages, and archers. All of them can walk, jump, and carry items. Instead of writing these common features again and again, we can create a base Player class and let other classes inherit from it.

Let's see this in action:

// This is our parent/base class
public class Player {
    String name;
    int health = 100;

    public void walk() {
        System.out.println(name + " is walking");
    }

    public void jump() {
        System.out.println(name + " jumped!");
    }
}

// Warrior inherits from Player using 'extends'
public class Warrior extends Player {
    // Warriors have a special sword attack
    public void swordAttack() {
        System.out.println(name + " swings their sword!");
    }
}

// Mage also inherits from Player
public class Mage extends Player {
    // Mages can cast spells
    public void castSpell() {
        System.out.println(name + " casts a magical spell!");
    }
}
Enter fullscreen mode Exit fullscreen mode

Why is this cool? 🌟

  1. Both Warrior and Mage automatically get all the features of Player
  2. They can still do their own special things (like swordAttack and castSpell)
  3. We write less code and keep things organized

Let's Use Our Classes!

public class GameDemo {
    public static void main(String[] args) {
        Warrior arthur = new Warrior();
        arthur.name = "Arthur";

        Mage merlin = new Mage();
        merlin.name = "Merlin";

        // Both can walk and jump
        arthur.walk();  // Output: Arthur is walking
        merlin.jump(); // Output: Merlin jumped!

        // Special abilities
        arthur.swordAttack(); // Output: Arthur swings their sword!
        merlin.castSpell();   // Output: Merlin casts a magical spell!
    }
}
Enter fullscreen mode Exit fullscreen mode

Making Things More Interesting: Override! πŸ”„

Sometimes we want to change how a child class behaves. We can do this using @Override:

public class Mage extends Player {
    // Mages jump differently - they float!
    @Override
    public void jump() {
        System.out.println(name + " floats magically in the air!");
    }

    public void castSpell() {
        System.out.println(name + " casts a magical spell!");
    }
}
Enter fullscreen mode Exit fullscreen mode

Protected vs Private vs Public πŸ”’

  • public: Everyone can use it
  • protected: Only the class itself and its children can use it
  • private: Only the class itself can use it
public class Player {
    public String name;        // Anyone can access
    protected int health;      // Only Player and its children
    private int secretPower;   // Only Player can access
}
Enter fullscreen mode Exit fullscreen mode

Real-World Example: Animal Kingdom 🐾

Let's see another example with animals:

public class Animal {
    protected String name;

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

    public void sleep() {
        System.out.println(name + " is sleeping");
    }
}

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

public class Cat extends Animal {
    public void meow() {
        System.out.println(name + " says: Meow!");
    }

    // Cats sleep differently!
    @Override
    public void sleep() {
        System.out.println(name + " is taking a cat nap");
    }
}
Enter fullscreen mode Exit fullscreen mode

Final Tips πŸ’‘

  1. A class can only extend one class in Java (single inheritance)
  2. Use extends keyword to inherit
  3. Use @Override when changing parent behavior
  4. Think about what should be public, protected, or private

Let's Learn Together! 🀝

I'd love to hear about your experiences with inheritance! Have you used it in any cool projects? Do you know any helpful resources or tutorials? Please share in the comments below!

Also, if you're interested in learning more, here are some topics you might want to explore:

  • Abstract classes
  • Interfaces
  • Multiple inheritance in Java (through interfaces)
  • The super keyword

Remember, the best way to learn is by doing. Try creating your own classes and experiment with inheritance!

This is just my way of understanding inheritance - I'd love to hear your thoughts and learn from your experiences! Feel free to share any helpful resources or alternative explanations in the comments. 😊

Top comments (2)

Collapse
 
madzimai profile image
Netsai

Image inheritance

Thanks to your article, I finally understand inheritance more clearly! In my recent project, I used inheritance to simplify repository creation. For example, in the image above, my UserProfileRepository extends Micronaut's CrudRepository, inheriting methods likesave, findById, and deleteById. This approach saves time by letting me focus on the unique logic of my app instead of rewriting basic CRUD operations. Your explanation really helped me connect the dotsβ€”thank you for sharing your insights!

Collapse
 
devsigma profile image
DevSigma

mmmh tasty