Table of Contents
ToggleIn OOPS, Inheritance is a fundamental concept in programming that allows you to create new classes based on existing ones. It enables a new class, known as the “child” or “subclass” to inherit the attributes and behaviours of an existing class, known as the “parent” or “superclass.”
In essence, inheritance allows you to build upon what’s already defined in a class, reusing and extending its features. This helps organise and structure code, making it more efficient and maintainable.
In this article we will see that what is hierarchical inheritance in Java and also see some of the example of hierarchical inheritance in Java.
What is Hierarchical Inheritance In Java?
Hierarchical inheritance in Java involves the creation of a class hierarchy where you have a single parent class, known as the superclass, and multiple child classes, known as subclasses. All of these subclasses inherit attributes and behaviours from the same parent class.
- Superclass (Parent Class): This is the top-level class in the hierarchy. It defines common attributes and behaviours that are shared by all the subclasses. In the context of hierarchical inheritance, there is only one superclass.
- Subclasses (Child Classes): These are the classes that inherit from the superclass. Each subclass extends the superclass by adding its own unique attributes and behaviours in addition to the ones inherited from the superclass. Multiple subclasses can exist in a hierarchical inheritance.
Let’s understand using hierarchical inheritance example in Java.
Hierarchical Inheritance Example In Java
To understand hierarchical inheritance in Java program better let’s see Vehicle hierarchical inheritance program in Java.
We can create a parent class called Vehicle that represents the common attributes and behaviours of all types of vehicles:
// Vehicle Class
public class Vehicle {
private String engineType;
private int wheelCount;
public void startEngine() {
//starting engine logic
}
public void applyBrakes() {
//braking logic
}
}
The Vehicle class contains engineType, wheelCount fields, and startEngine(), applyBrakes() methods that any vehicle would need. We can now create child classes Car and Bike that inherit from the parent Vehicle class:
// Sub Classes
public class Car extends Vehicle {
private int numDoors;
public void openDoors() {
//door opening logic
}
}
public class Bike extends Vehicle {
private int numGears;
public void paddle() {
//paddle logic
}
}
The Car and Bike classes use the extends keyword to establish the hierarchical inheritance relationship with the Vehicle parent.
They inherit the engineType, wheelCount, startEngine() and applyBrakes() members from Vehicle without having to redefine them. At the same time, they define their own fields and methods like numDoors, openDoors(), numGears, paddle() that are specific to cars and bikes respectively.
This demonstrates hierarchical inheritance in a simple vehicle hierarchy example. Multiple subclasses leverage reused logic from the single parent while having their own customized features.
Real World Example Of Hierarchical Inheritance In Java
Let’s look at some of the real world example of Hierarchical Inheritance In Java
Game Development
In game development, hierarchical inheritance is a powerful concept used to create different character types while efficiently managing shared attributes and behaviours. Here’s how it works:
// Base Character class
class Character {
String name;
int health;
int attackPower;
void takeDamage(int damage) {
health -= damage;
}
}
- The
Character
class acts as the foundation for all game characters. It contains common attributes such asname
,health
, andattackPower
. - The
takeDamage(int damage)
method allows all characters to receive damage and update their health.
// Specific character types inheriting from Character
class Soldier extends Character {
// Additional attributes or methods specific to soldiers
void meleeAttack() {
// Melee attack logic
}
}
class Archer extends Character {
// Additional attributes or methods specific to archers
void shootArrow() {
// Shooting arrow logic
}
}
class Mage extends Character {
// Additional attributes or methods specific to mages
void castSpell() {
// Spell casting logic
}
}
- Specific character types like
Soldier
,Archer
, andMage
inherit all the attributes and methods from theCharacter
class. - They can also add their own unique attributes and methods. For example,
Soldier
has ameleeAttack()
method, whileArcher
has ashootArrow()
method.
Web Development
In web development, hierarchical inheritance simplifies the management of different content types while reusing essential information. Here’s an example:
// Parent Content class for articles, pages, etc.
class Content {
String title;
String text;
String author;
}
The Content
class serves as the common base for various types of content on a website, including attributes like title
, text
, and author
.
// Specific content types inheriting from Content
class BlogPost extends Content {
// Additional attributes specific to blog posts
String[] tags;
}
class Article extends Content {
// Additional attributes specific to articles
String publicationDate;
}
class Page extends Content {
// Additional attributes specific to pages
int pageCount;
}
- Content types like
BlogPost
,Article
, andPage
inherit core attributes from theContent
class. - They extend the hierarchy by introducing their unique attributes. For example,
BlogPost
includes an array oftags
, whileArticle
has apublicationDate
.
Graphical Interface (GUI) Development
In graphical user interface (GUI) development, hierarchical inheritance streamlines the creation of reusable components with specific functionalities. Here’s a simplified example:
// Base Component class for graphical elements
class Component {
int size;
int positionX;
int positionY;
String color;
// Common methods for all components
void draw() {
// Drawing logic
}
}
The Component
class defines the fundamental properties shared by all graphical elements in the GUI, such as size
, positionX
, positionY
, and color
.
// Specific component types inheriting from Component
class Button extends Component {
// Additional methods and attributes specific to buttons
void click() {
// Button click logic
}
}
class TextBox extends Component {
// Additional methods and attributes specific to text boxes
void setText(String text) {
// Set text logic
}
}
class Panel extends Component {
// Additional methods and attributes specific to panels
void addComponent(Component component) {
// Add component logic
}
}
- Component types like
Button
,TextBox
, andPanel
inherit the fundamental properties and methods from theComponent
class. - They specialise by introducing their unique methods and attributes. For instance,
Button
has aclick()
method,TextBox
has asetText(String text)
method, andPanel
can manage a collection of components withaddComponent(Component component)
.
Hierarchical Inheritance in Java Program
Hierarchical inheritance in Java is a scenario where one parent class is inherited by multiple child classes. It’s a way to create a hierarchy of classes that share common features while also introducing specific features in the child classes.
Here’s an example to illustrate hierarchical inheritance:
- Parent Class (Animal): A base class that includes properties and methods common to all animals.
- Child Classes (Dog, Cat, Bird): These classes inherit from the Animal class and can have their own specific properties and methods in addition to what they inherit from Animal.
Java Code Example:
// Parent class
class Animal {
void eat() {
System.out.println("Eating...");
}
}
// Child class 1
class Dog extends Animal {
void bark() {
System.out.println("Barking...");
}
}
// Child class 2
class Cat extends Animal {
void meow() {
System.out.println("Meowing...");
}
}
// Child class 3
class Bird extends Animal {
void fly() {
System.out.println("Flying...");
}
}
// Main class to test the inheritance
public class TestInheritance {
public static void main(String args[]) {
Dog d = new Dog();
Cat c = new Cat();
Bird b = new Bird();
d.eat();
d.bark();
c.eat();
c.meow();
b.eat();
b.fly();
}
}
Output
Eating...
Barking...
Eating...
Meowing...
Eating...
Flying...
In this example:
- When the
Dog
objectd
callseat()
andbark()
, it first prints"Eating..."
from the inheritedeat()
method in theAnimal
class, followed by"Barking..."
from its ownbark()
method. - Similarly, the
Cat
objectc
callseat()
andmeow()
, resulting in"Eating..."
and"Meowing..."
respectively. - The
Bird
objectb
callseat()
andfly()
, outputting"Eating..."
and"Flying..."
.
This example shows how hierarchical inheritance allows for code reusability and organisation by having a common base class from which other classes derive common behaviours and properties.
How is Hierarchical Inheritance Useful?
Hierarchical inheritance in Java program provides several advantages when used appropriately:
Eliminates Code Duplication
- Common attributes and behaviours defined in a parent class are inherited by all child classes.
- This eliminates duplicate code as child classes can rely on the inherited features.
- For example, a Vehicle class contains shared logic like startEngine() that Car and Bike subclasses inherit without rewriting.
Clean Hierarchical Relationships
- Hierarchical inheritance allows modelling relationships between classes that mirror real-world taxonomies.
- For example, Vehicle superclass is a general parent category with subclasses Car, Bike being more specific.
Improved Organization
- Hierarchical inheritance provides structure that makes complex software more manageable.
- Related classes are organised under parent-child relationships making them easier to understand.
- This is especially useful when designing large object-oriented systems.
Easier Maintenance
- When a change is needed in shared parent class logic, it can be done once and inherited everywhere.
- For example, changing how startEngine() works in Vehicle will automatically apply to all subclasses.
- This makes maintenance simpler compared to changing duplicate code everywhere.
Key TakeAways
To Conclude
- Hierarchical inheritance in Java program involves the creation of a class hierarchy where you have a single parent class and multiple child classes.
- Child classes automatically inherit attributes and behaviors from parent classes. This eliminates duplicate code.
- Child classes can override inherited methods from the parent to provide specialized implementations.
- In addition to inherited members, child classes can declare their own unique fields and methods.
- Hierarchical inheritance structures code logically, mimicking real-world taxonomies. This makes large systems more organized and maintainable.
Checkout more Java Tutorials here.
FAQ
What is a hierarchy in Java?
In Java, a hierarchy typically refers to the arrangement of classes and their relationships in a tree-like structure. This structure is often used in class inheritance, where a superclass (parent class) can have multiple subclasses (child classes) that inherit its attributes and methods.
What is hierarchical abstraction in Java?
Hierarchical abstraction is a concept in Java where you create a hierarchy of classes with a common base class (superclass) that defines shared attributes and behaviors. Subclasses can then extend this base class to inherit and specialize its properties while adding their own unique characteristics.
What is a multilevel inheritance?
Multilevel inheritance in Java is when a class inherits from another class, which in turn inherits from another class. It creates a chain of inheritance where each class extends the previous one, forming a hierarchical structure.
What are different types of inheritance?
There are different types of inheritance in Java:
- Single Inheritance: A class can inherit from only one superclass.
- Multiple Inheritance (through interfaces): A class can implement multiple interfaces, effectively inheriting behavior from multiple sources.
- Multilevel Inheritance: As mentioned earlier, it involves a chain of inheritance.
- Hierarchical Inheritance: Multiple subclasses inherit from a single superclass.
- Hybrid Inheritance: A combination of two or more types of inheritance, often involving multiple and hierarchical inheritance together. Java supports multiple inheritance through interfaces but not through classes.