Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
4 views
in Java by (55.6k points)
Can anyone explain to me about polymorphism with examples?

1 Answer

0 votes
by (119k points)
edited by

Polymorphism means multiple forms that mean the same object can be used to different tasks.

Operator overloading is a type of polymorphism, using the same operator for different functions

Example: In Java, + operator can be used to concatenate two string and also can be used to add two numbers.

int x = 2;

int y = 3;

int sum = x + y;   // output = 5  

String fName = "ABC";

String lName = "DEF

name = fName + lName;   //  output = ABC DEF

Method Overloading is another type of polymorphism in which the method name will be the same in different classes. That particular method will be called based on the object name.

Example: In this example sound() method is used in different classes. If c1.Sound() is executed sound() method of the class cow will be called. If l1.sound() is executed sound() method of class Lion will be called.

abstract class Animal{

   public abstract void sound();

}

class Lion extends Animal {

      public void sound() {

      System.out.println("roar roar..");

   }

}

class Cow extends Animal {

      public void sound() {

      System.out.println("Moo moo..");

   }

}

class Main {

   public static void main(String[] args) {

     Lion  l1 = new Lion();

      l1.sound(); 

      Cow c1 = new Cow();

      c1.sound();

   }

}

In case if you are interested in Java, you can take up this Java course by intellipaat

You can watch this video on Java for a better explanation:

Related questions

0 votes
1 answer
asked Mar 21, 2021 in Java by Jake (7k points)
0 votes
1 answer
0 votes
1 answer
asked May 17, 2023 in Java by neelimakv (37.3k points)

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...