Preparing for Java and Spring Boot Interview?

Join my Newsletter, its FREE

Friday, September 29, 2023

Polymorphism and Inheritance Example in Java

Hello guys, If you are new to Java or Object oriented programming and wondering what is Polymorphism and Inheritance and what are their use then you have come to the right place. Polymorphism and Inheritance are two fundamental concepts in object-oriented programming that allow for flexibility and reusability of code. In Java, these concepts are closely related and often go hand in hand. Java Programming provides a couple of way to implement Inheritance like extending a class or implementing an interface. Similarly they provide overloading and overriding for Polymorphism. In the past, I have shared 40 object oriented questions as well as 23 design patterns and In this article, we'll explore these concepts with a practical example.

Inheritance: The Foundation

In Object Oriented programming, Inheritance is a mechanism that allows one class (the subclass or child class) to inherit the properties and behaviors of another class (the superclass or parent class). This promotes code reuse and establishes a hierarchical relationship between classes.

Let's create a simple example to understand inheritance in Java:

class Animal {
    void makeSound() {
        System.out.println("Some generic sound");
    }
}

class Dog extends Animal {
    @Override
    void makeSound() {
        System.out.println("Woof!");
    }
}

In this example, we have an Animal superclass and a Dog subclass that inherits from Animal. The Dog class overrides the makeSound method to provide its specific implementation.

Here is another example of Inheritance to create type hierarchy in Java:

Polymorphism and Inheritance Example in Java



Polymorphism: Many Forms

Polymorphism is the ability of objects of different classes to respond to the same method call in a way that is appropriate for their class. It allows you to write more generic code that can work with objects of different types, promoting flexibility.

public class PolymorphismExample {
    public static void main(String[] args) {
        Animal myPet = new Dog();
        myPet.makeSound(); // Calls Dog's makeSound
    }
}

In this example, we declare an Animal reference myPet that points to a Dog object. When we call myPet.makeSound(), it invokes the makeSound method from the Dog class, demonstrating polymorphism.


Polymorphism and Inheritance Example

Here is another example where I have combined both Polymorphism and Inheritance to demonstrate the power of object oriented programming and the flexibility it provides. 


/**
* An example of Polymorphism and Inheritance in Java. In Java * Polymorphism is closely tied to Inheritance, and it only work if all * classes are part of same type hierarchy. 
* It helps you to write flexible code, which can even support
* things not available today.
*
* Constructor is not inherited in Java.
*
* @author javinpaul
*/
public class InheritanceAndPolymorphismDemo{

    public static void main(String args[]) {

        Mango mango = new Mango();
        Apple apple = new Apple();

        // You can pass object to subclass to a method which
        // accept type of super class
        print(mango);
        print(apple);

     // A reference variable of type super class, can
        // Point object of subclass
        Fruit fruit = new Apple(); //OK
        fruit = new Mango(); //OK
        String name = fruit.name(); // will call Mango's name() method
   }

    /**
     * prints name of the fruit, supports polymorphism
     *
     * @param f
     */
    public static void print(Fruit f) {
        System.out.printf("You have got a %s %n", f.name());
    }

}

enum Color {

    RED, GREEN, BLUE, YELLOW;
}

abstract class Fruit {

    abstract String name();

    abstract Color color();
}

class Mango extends Fruit {

    @Override
    public String name() {
        return "Mango";
    }

    @Override
    public Color color() {
        return Color.YELLOW;
    }
}

class Apple extends Fruit {

    @Override
    public String name() {
        return "Apple";
    }

    @Override
    public Color color() {
        return Color.RED;
    }

}

Expalnation:

Now, let's understand what's going on here. The Java code demonstrates the principles of inheritance, polymorphism, and object-oriented programming. It defines a hierarchy of classes related to fruits and showcases how objects of these classes can be manipulated.

The code begins by defining two classes, Mango and Apple, both of which are subclasses of an abstract class called Fruit. Each subclass (Mango and Apple) overrides the name() and color() methods to provide specific implementations for their respective fruits.

In the InheritanceAndPolymorphismDemo class's main method, instances of Mango and Apple are created: mango and apple.

The print() method is used to demonstrate polymorphism. This method accepts an argument of type Fruit, which is the superclass of both Mango and Apple. This means it can accept objects of either type. Inside the print method, it calls the name() method on the provided Fruit object to print the name of the fruit. This showcases polymorphism because the appropriate name() method of the actual object type (Mango or Apple) is called at runtime.

In the main method, you'll see how polymorphism works. print(mango) and print(apple) are called, and they both correctly print the names of the fruits passed to them.

The code also demonstrates how superclass references can point to subclass objects. It creates a fruit reference variable of type Fruit and assigns it first to a Mango object and then to an Apple object. This demonstrates that you can use a superclass reference to refer to objects of its subclass.

Finally, the name() method is called on the fruit reference. Since fruit refers to a Mango object, it calls the name() method of Mango, which prints "Mango."

In summary, this code illustrates key concepts in object-oriented programming, including inheritance, polymorphism, and how superclass references can be used to work with subclass objects, making your code more flexible and extensible.

That's all about Inheritance and Polymorphism example in Java. Polymorphism and inheritance are powerful concepts in Java that enable code organization, reusability, and flexibility. They form the basis of object-oriented programming and are essential for building maintainable and extensible software. By understanding and utilizing these concepts effectively, you can write more elegant and efficient Java code.

No comments :

Post a Comment