Logo

dev-resources.site

for different kinds of informations.

Polymorphism in Java.

Published at
1/24/2022
Categories
java
beginners
programming
inheritance
Author
isaacttonyloi
Author
13 person written this
isaacttonyloi
open
Polymorphism in Java.

Derived from two Greek words ‘poly’ and ‘morphs ’, the word polymorphism refers to many forms. It is one of the most important concepts in Object-Oriented programming.

There are two forms of Polymorphism in java. These include:

  • Runtime polymorphism

  • Compile-time polymorphism

Polymorphism allows us to use the same entity i.e a method to perform different actions in different situations. In the example below we are using the same method to perform different actions under the same name.

class AnimalsEat {
    public void eat() {
        System.out.println("All animals eat !");
    }
}
class Cows extends AnimalsEat {
    public void eat() {
        System.out.println("Cows eat grass !");
    }
}
class Dogs extends AnimalsEat {
    public void eat() {
        System.out.println("Dogs eat dog food !");
    }

}

class Main {
    public static void main(String[] args) {
        Cows obj1 = new Cows();
        obj1.eat();

        Dogs obj2 = new Dogs();
        obj2.eat();
    }
}
Enter fullscreen mode Exit fullscreen mode

Output

Cows eat grass !
Dogs eat dog food !
Enter fullscreen mode Exit fullscreen mode

In the code above we have created a superclass named AnimalsEat with the method,eat() from which two subclasses namely: the Dogs class and the Cows class have inherited from.
The method eat() has been used in these two classes to render different messages, this method, therefore, has different forms in these two subclasses.

Now polymorphism can be achieved in three major ways in Java and these include through:

  • Method Overloading

  • Operator Overloading

  • Method Overriding

Method Overloading.

Method overloading is a scenario in Java where a class is allowed to have several methods with the same name provided that these methods have different parameters. Now parameters in these methods can be different in the sense that: the methods have an unequal number of parameters, parameters are of different data types, or the sequence of these parameters varies.

Here is an example:


class AddNumbers {
    public int sum(int a, int b) {
        int result = a + b;
        return result;


    }

    public double sum(double c, double d) {
        double result2 = c + d;
        return result2;

    }


}
class Main {
    public static void main(String[] args) {
        AddNumbers obj = new AddNumbers();
        int result = obj.sum(3, 4);
        System.out.println(result);

        double result2 = obj.sum(34.5, 34.2);
        System.out.println(result2);
    }

}
Enter fullscreen mode Exit fullscreen mode

Output

7
68.7
Enter fullscreen mode Exit fullscreen mode

In the code above we have created a class named AddNumbers, I agree it is not a great choice when it comes to naming a class. However, as you can see we have overloaded the method sum(), by having parameters of different data types. The compiler in this case is responsible for distinguishing the method, and therefore this is known as compile-time polymorphism.

Method Overriding.

Method overriding can be achieved through inheritance in java. Inheritance allows us to derive a new class from a preexisting class. Inheritance also promotes code reusability by allowing one class known as the subclass or child class to inherit methods and fields from another class known as the superclass or the parent class.
Now method overriding occurs when a method is defined with the same name both in the subclass and the superclass. Here is an example of method overriding in java.

class Fruits {
    public void display() {
        System.out.println("Most fruits turn yellow when ripe !");
    }
}
class Oranges extends Fruits {
    @Override
    public void display() {
        System.out.println("Oranges turn yellow when ripe !");
    }
}
class Main {
    public static void main(String[] args) {
        //object for Fruit class
        Fruits obj = new Fruits();
        obj.display();
        //object for Oranges class
        Oranges obj1 =  new Oranges();
        obj1.display();
    }
}

Enter fullscreen mode Exit fullscreen mode

Output

Most fruits turn yellow when ripe !
Oranges turn yellow when ripe !
Enter fullscreen mode Exit fullscreen mode

In the example above the display() method in the Oranges class overrides the method in the superclass. However, using distinct objects for each class we have called both methods.
Here since the method that is called is determined when the program is being executed, this is referred to as Run-time polymorphism.

Operator Overloading.

In java and most programming languages operators such as the + operator can be overloaded. For instance, when the addition operator is used with numbers it is used to perform an arithmetic operation. However, when the same operator is used with String it is intended to perform concatenation.

Code

int num1  = 12;
int num2 = 14;
int sum = num1 + num2;

    //output = 26
Enter fullscreen mode Exit fullscreen mode

However, when the same operator is used with String it is intended to perform concatenation.

Code
String firstname = 'Isaac';
String lastname = 'Tonyloi';
String fullname = firstname + lastname;
//output = Isaac Tonyloi
Enter fullscreen mode Exit fullscreen mode

Connect with Isaac Tonyloi.

inheritance Article's
30 articles in total
Favicon
Code Smell 286 - Overlapping Methods
Favicon
Understanding Traits in PHP and How They Differ from Inheritance
Favicon
Understanding Classes and Inheritance in JavaScript
Favicon
Mastering Generalization in OOP: Techniques and Examples
Favicon
Upcasting — Using a Superclass Reference for a Subclass Object
Favicon
Mapping inheritance hierarchies with MapStruct
Favicon
Python Inheritance Explained: Types, Examples, and Best Practices
Favicon
Mastering TypeScript: Understanding the Power of extends
Favicon
PHP: Herança vs. Composição
Favicon
Method Resolution Order in Python 3
Favicon
Why we don't use RemoteWebDriver driver = new ChromeDriver()
Favicon
Understanding JavaScript Inheritance: A Deep Dive into Prototypal and Constructor Patterns
Favicon
Understanding Inheritance and Polymorphism: Simplified OOP Concepts
Favicon
JS Inheritance - Part 2: Factory Functions vs. Classes
Favicon
Inheritance with access-specifier in cpp
Favicon
Inheritance in Dart
Favicon
RoR - extend, < (inheritance), include - know the difference
Favicon
Inheritance vs composition: a fight against Egyptian gods
Favicon
Object Oriented Concept - Inheritance
Favicon
Exploring Component Inheritance in Aventus
Favicon
Python Inheritance
Favicon
Inheritance vs Composition: Using a Role-Playing Game in JavaScript as an Example
Favicon
PostgreSQL - Partitioning & Inheritance
Favicon
Prototype and Prototypical Inheritance
Favicon
Ruby - Inheritance
Favicon
MultiLevel Inheritance in Java
Favicon
Overloading vs Overriding in Typescript
Favicon
Java Error - at least one public class is required in main file
Favicon
Polymorphism in Java.
Favicon
Method Overriding in Java.

Featured ones: