Java / Object-Oriented Programming in Java

Implementing Inheritance and Polymorphism

In this tutorial, we will delve into the concepts of inheritance and polymorphism in Java. You'll learn how to reuse code and perform a single action in different ways.

Tutorial 3 of 5 5 resources in this section

Section overview

5 resources

Explores OOP principles such as classes, objects, inheritance, polymorphism, and abstraction.

1. Introduction

Goal of the Tutorial

This tutorial aims to provide a comprehensive understanding of inheritance and polymorphism in Java. We'll be implementing these concepts through practical examples.

Learning Outcomes

By the end of this tutorial, you will:
- Understand the concepts of inheritance and polymorphism
- Be able to implement inheritance in Java
- Know how to use polymorphism in Java

Prerequisites

Before starting this tutorial, you should have:
- Basic knowledge of Java programming language
- Installed Java Development Kit (JDK) on your computer
- Installed an Integrated Development Environment (IDE), such as Eclipse, IntelliJ IDEA, or NetBeans

2. Step-by-Step Guide

Inheritance

Inheritance in Java is a mechanism where one class acquires the properties (methods and fields) of another. With the use of inheritance, information is managed in a hierarchical order.

To achieve inheritance, we use the extends keyword.

class SuperClass {
  // fields and methods
}
class SubClass extends SuperClass {
  // fields and methods
}

Polymorphism

Polymorphism in Java is a concept by which we can perform a single action in different ways. We can perform polymorphism by method overloading and method overriding.

  • Method Overloading: When a class has two or more methods with the same name but different parameters, it's known as method overloading.
  • Method Overriding: If a subclass provides a specific implementation of a method that is already provided by its parent class, it's known as method overriding.

3. Code Examples

Example of Inheritance

Here is a simple example of inheritance where a child class inherits the properties of a parent class.

class Animal {  
  void eat() {
    System.out.println("eating...");
  }
}  

class Dog extends Animal {  
  void bark() {
    System.out.println("barking...");
  }
}  

class TestInheritance {
  public static void main(String args[]) {  
    Dog d = new Dog();  
    d.bark();  
    d.eat();  
  }
}

In this example, Dog class (subclass) is inheriting the Animal class (superclass). Hence, Dog can access the eat() method of Animal class.

The expected output is:

barking...
eating...

Example of Polymorphism

Here is a simple example of polymorphism where one task is performed in different ways.

class Animal {
  void sound() {
    System.out.println("Animal is making a sound");
  }
}

class Dog extends Animal {
  void sound() {
    System.out.println("Dog is barking");
  }
}

class Cat extends Animal {
  void sound() {
    System.out.println("Cat is meowing");
  }
}

class Main {
  public static void main(String args[]) {
    Animal a1, a2, a3;
    a1 = new Dog();
    a2 = new Cat();
    a3 = new Animal();

    a1.sound();
    a2.sound();
    a3.sound();
  }
}

In this example, we have three classes: Animal, Dog, and Cat. The Dog and Cat classes override the sound() method of the Animal class. In the main method, we create objects of the Dog, Cat, and Animal classes but reference them with a variable of type Animal (superclass).

The expected output is:

Dog is barking
Cat is meowing
Animal is making a sound

4. Summary

In this tutorial, we've discussed the concepts of inheritance and polymorphism in Java. We've also seen how these concepts can be implemented through practical examples.

To further your understanding, you can explore topics like multiple inheritance, multilevel inheritance, and hybrid inheritance. Check out the official Java documentation for additional resources.

5. Practice Exercises

  1. Exercise 1: Create a superclass named 'Shape' with a method to calculate area. Now, create two subclasses 'Rectangle' and 'Circle' and override the area method.

  2. Exercise 2: Implement polymorphism by creating a superclass named 'Animal' with a method 'sound'. Now, create three subclasses 'Dog', 'Cat', 'Cow' and override the sound method.

Solutions and explanations of these exercises will be provided in the next tutorial. Remember, practice is key to mastering these concepts. Happy coding!

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

Color Palette Generator

Generate color palettes from images.

Use tool

Scientific Calculator

Perform advanced math operations.

Use tool

Random Password Generator

Create secure, complex passwords with custom length and character options.

Use tool

Date Difference Calculator

Calculate days between two dates.

Use tool

AES Encryption/Decryption

Encrypt and decrypt text using AES encryption.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help