Java Programming - Lesson 17
Understanding Inheritance in Java with Practical Examples
Introduction
Have you ever wondered how programmers can create multiple classes that share common properties and behaviours without repeatedly writing the same code?
The answer lies in one of the most important principles of Object-Oriented Programming (OOP): Inheritance.
Inheritance is a powerful feature of Java that allows one class to acquire accessible properties and methods from another class. It encourages code reuse, simplifies program development, and makes applications easier to maintain and expand.
In this Java Programming tutorial, we will explore inheritance using a practical example involving animals in a zoo. We will also examine method overriding, the extends keyword, dynamic method dispatch, and the relationship between inheritance and polymorphism.
Whether you are a beginner or an aspiring Java developer, this tutorial will help you understand how inheritance works and why it is important.
1. What Is Inheritance in Java?
Inheritance is an Object-Oriented Programming mechanism through which one class acquires accessible fields and methods from another class.
The class providing the inherited features is called the parent class or superclass, while the class receiving them is called the child class or subclass.
For example, consider three animals:
Sheep
Lion
Zebra
Although these animals have different characteristics, they share some common features. They all eat, and each has certain behaviours when interacting with people.
Rather than creating completely independent classes containing similar methods, we can create a general class called Animal.
The Sheep, Lion, and Zebra classes can then inherit from Animal.
This is the basic idea behind inheritance.
2. Creating a Parent Class in Java
Let's create a simple Java class called Animal.
public class Animal {
public void feed() {
System.out.println("Animal eats.");
}
public void pet() {
System.out.println("Animal gets petted.");
}
}
Our Animal class contains two methods:
feed(): Represents the general feeding behaviour of an animal.
pet(): Represents the general response when someone attempts to pet an animal.
These methods provide common functionality that other animal classes can inherit.
3. Creating Child Classes Using extends
Java uses the extends keyword to establish inheritance between classes.
For example, we can create a Sheep class that inherits from Animal:
public class Sheep extends Animal {
}
We can do the same for Lion:
public class Lion extends Animal {
}
And Zebra:
public class Zebra extends Animal {
}
All three classes now inherit the accessible methods of Animal.
This means that objects created from Sheep, Lion, and Zebra can use the inherited feed() and pet() methods even though these methods were originally defined in Animal.
4. Parent Classes and Child Classes
Inheritance relationships have several commonly used names.
Parent Class Terminology
Child Class Terminology
Parent class
Child class
Superclass
Subclass
Base class
Derived class
Generalized class
Specialized class
For example, Animal is the superclass, while Sheep is its subclass.
Understanding these terms will help you follow Java documentation and programming discussions.
5. Understanding Single Inheritance
Java supports single inheritance when dealing with classes.
This means a class can directly extend only one other class.
For example:
public class Lion extends Animal {
}
However, Java does not allow the following:
// Invalid Java syntax
public class Lion extends Animal, Carnivore {
}
A class can extend one class, although that parent class may itself extend another class.
Java also supports multiple inheritance of type through interfaces.
6. What Is Method Overriding?
Although our animal classes inherit the general methods from Animal, we may want each animal to behave differently.
For instance, a sheep should have a different feeding behaviour from a lion.
We can achieve this by redefining the inherited methods inside the child classes.
This is called method overriding.
Consider the following example:
public class Sheep extends Animal {
@Override
public void feed() {
System.out.println("Sheep eats grass happily.");
}
@Override
public void pet() {
System.out.println("Sheep pushes against your leg.");
}
}
The Sheep class now has its own implementations of feed() and pet().
The @Override annotation tells the compiler that we intend to override methods inherited from the parent class.
This helps identify mistakes, such as misspelling a method name or using an incompatible method signature.
7. Testing Inheritance
What happens if we remove the overridden methods from the Sheep class?
The Sheep object will simply use the inherited methods from Animal.
For example:
Animal animal = new Animal();
animal.feed();
animal.pet();
Output:
Animal eats.
Animal gets petted.
Similarly, if a Sheep class does not override these methods, an instance of Sheep can use the inherited implementations.
This demonstrates how inheritance allows child classes to reuse existing functionality.
8. Using Inheritance with Arrays
One of the major advantages of inheritance is that it allows different child-class objects to be treated through a common parent-class reference.
Consider the following example:
Sheep sheep = new Sheep();
Lion lion = new Lion();
Zebra zebra = new Zebra();
Animal[] animals = {sheep, lion, zebra};
Although these objects belong to different classes, they can all be stored in an Animal array because each class inherits from Animal.
We can then iterate through the array:
for (Animal animal : animals) {
animal.feed();
animal.pet();
}
Java executes the appropriate overridden methods belonging to the actual objects.
This makes our program more flexible and reduces the amount of repetitive code.
9. Understanding Dynamic Method Dispatch
When we invoke an overridden method through a parent-class reference, Java determines the appropriate implementation at runtime.
This is known as dynamic method dispatch.
Consider:
Animal animal = new Sheep();
animal.feed();
Although the reference variable is declared as Animal, the actual object is Sheep.
Therefore, Java executes the overridden feed() method in the Sheep class.
This is an example of runtime polymorphism.
The declared reference type determines which methods are accessible, while the actual object type determines the overridden method implementation that executes.
10. Passing Objects as Method Arguments
Inheritance also allows us to create methods that accept objects of a general parent class.
For example:
public void visitAnimal(Animal animal) {
animal.feed();
animal.pet();
}
We can pass different animal objects to this method:
visitAnimal(new Sheep());
visitAnimal(new Lion());
visitAnimal(new Zebra());
The method works with all three objects without needing separate implementations for each animal.
This is one of the most useful applications of inheritance and polymorphism in Java.
11. Real-World Applications of Inheritance
Inheritance is widely used in software development.
Here are some practical examples:
Employee Management Systems
A general Employee class could contain common information such as employee name, identification number, and department.
Specialized classes such as Manager, Developer, and Accountant could inherit from Employee.
Banking Applications
A general Account class could provide common banking operations, while SavingsAccount and CurrentAccount could implement their specialized features.
Educational Management Systems
A general Person class could be inherited by Student, Teacher, and Administrator classes.
E-commerce Applications
A general Product class could provide common product information, while specialized classes could represent electronics, clothing, and furniture.
These examples demonstrate how inheritance helps organize complex applications.
12. Practical Exercise
To test your understanding, create a Java project called Animal Kingdom.
Complete the following tasks:
Create a parent class called Animal.
Add two methods: makeSound() and move().
Create three child classes: Dog, Cat, and Bird.
Make each child class extend Animal.
Override the two methods in each child class.
Create an array of Animal objects containing instances of Dog, Cat, and Bird.
Use a loop to invoke the methods on each object.
Observe how Java executes the appropriate methods at runtime.
Challenge: Create another method called describeAnimal() that accepts an Animal object as an argument and displays its behaviour.
Conclusion
Inheritance is one of the foundations of Object-Oriented Programming in Java.
It allows programmers to create general classes containing common features and specialized classes that extend those features to meet specific requirements.
Through the extends keyword, method overriding, arrays, and dynamic method dispatch, we can develop applications that are more reusable, flexible, and easier to maintain.
As you continue learning Java, remember that inheritance is closely connected to another important OOP principle: polymorphism.
Understanding these concepts will strengthen your programming skills and prepare you to develop more sophisticated Java applications.
Keep learning. Keep creating. Keep growing!
Creative Skills & Hobbies Hub is dedicated to promoting creativity, knowledge, practical skills, innovation, and personal development.
Our goal is to help individuals discover their potential, develop useful abilities, and transform knowledge and creativity into opportunities.
Explore more educational resources and tutorials on our platform.


Comments
Post a Comment
Welcome to Creative Skills & Hobbies Hub!
This blog is dedicated to recognizing, showcasing, and promoting diverse creative skills and hobbies, with the aim of helping individuals discover and nurture their own creative potentials, etc. We encourage you to share your thoughts, ask questions, and engage with our community.
Your voice matters! Whether you have a new hobby to explore, insights to offer, or creative stories to tell, we’d love to hear from you. Leave a comment below and join the conversation!