Polymorphism in Java with Examples in 2023

0
965
Polymorphism in Java with Examples in 2023


Polymorphism is the flexibility of an object to tackle totally different kinds. In Java, polymorphism refers back to the means of a category to offer totally different implementations of a technique, relying on the kind of object that’s handed to the tactic.

To put it merely, polymorphism in Java permits us to carry out the identical motion in many various methods. Any Java object that may go a couple of IS-A check is polymorphic in Java. Therefore, all of the Java objects are polymorphic because it has handed the IS-A check for their very own sort and for the category Object.

This article additionally talks about two varieties of polymorphism in Java: compile time polymorphism and runtime polymorphism, Java polymorphism examples, methodology overloading, methodology overriding, why to make use of polymorphism in java, java programming, and lots of extra.

What is Polymorphism in Java?

Polymorphism in Java is the duty that performs a single motion in numerous methods.

So, languages that don’t assist polymorphism usually are not ‘Object-Oriented Languages’, however ‘Object-Based Languages’. Ada, for example, is one such language. Since Java helps polymorphism, it’s an Object-Oriented Language.

Polymorphism happens when there may be inheritance, i.e., many courses are associated to one another.

Inheritance is a strong characteristic in Java. Java Inheritance lets one class purchase the properties and attributes of one other class. Polymorphism in Java permits us to make use of these inherited properties to carry out totally different duties. Thus, permitting us to realize the identical motion in many various methods.

What is Polymorphism?

The derivation of the phrase Polymorphism is from two totally different Greek words- poly and morphs. “Poly” means quite a few, and “Morphs” means kinds. So, polymorphism means innumerable kinds. Polymorphism, due to this fact, is likely one of the most vital options of Object-Oriented Programming.

Must Learn Core Java Topics

Real-Life Examples of Polymorphism

An particular person can have totally different relationships with totally different individuals. A lady is usually a mom, a daughter, a sister, and a pal, all on the similar time, i.e. she performs different behaviors in numerous conditions.

The human physique has totally different organs. Every organ has a unique perform to carry out; the guts is chargeable for blood circulation, the lungs for respiration, the mind for cognitive exercise, and the kidneys for excretion. So we’ve a normal methodology perform that performs in a different way relying upon the organ of the physique. 

Polymorphism in Java Example

A superclass named “Shapes” has a technique referred to as “area()”. Subclasses of “Shapes” could be “Triangle”, “circle”, “Rectangle”, and so forth. Each subclass has its approach of calculating space. Using Inheritance and Polymorphism means, the subclasses can use the “area()” methodology to search out the world’s formulation for that form.

class Shapes {
  public void space() {
    System.out.println("The formulation for space of ");
  }
}
class Triangle extends Shapes {
  public void space() {
    System.out.println("Triangle is ½ * base * peak ");
  }
}
class Circle extends Shapes {
  public void space() {
    System.out.println("Circle is 3.14 * radius * radius ");
  }
}
class Main {
  public static void predominant(String[] args) {
    Shapes myShape = new Shapes();  // Create a Shapes object
    Shapes myTriangle = new Triangle();  // Create a Triangle object
    Shapes myCircle = new Circle();  // Create a Circle object
    myShape.space();
    myTriangle.space();
    myShape.space();
    myCircle.space();
  }
}

Output:

The formulation for the world of the Triangle is ½ * base * peak
The formulation for the world of the Circle is 3.14 * radius * radius

class Shape {
    public void draw() {
        System.out.println("Drawing a form");
    }
}

class Circle extends Shape {
    @Override
    public void draw() {
        System.out.println("Drawing a circle");
    }
}

class Square extends Shape {
    @Override
    public void draw() {
        System.out.println("Drawing a sq.");
    }
}

class Main {
    public static void predominant(String[] args) {
        Shape s1 = new Circle();
        Shape s2 = new Square();

        s1.draw(); // Output: "Drawing a circle"
        s2.draw(); // Output: "Drawing a sq."
    }
}

In this instance, we’ve a base class Shape with a single methodology draw() that prints “Drawing a shape” to the console. We then create two subclasses, Circle and Square, that override the draw() methodology to print “Drawing a circle” and “Drawing a square” respectively.

In the predominant methodology, we create two cases of the Shape class, s1 and s2, which are literally cases of the Circle and Square subclasses. When we name the draw() methodology on these objects, the right implementation is known as primarily based on the precise sort of the thing, that is run-time polymorphism. The program will output: “Drawing a circle” and “Drawing a square”

In this instance, the draw() methodology is overridden within the subclasses, and this enables for this system to find out which methodology to make use of at runtime. This is called runtime polymorphism or dynamic polymorphism, Because at runtime the JVM determines the precise sort of the thing and calls the corresponding methodology.

Also Read: OOPs ideas in Java

Types of Polymorphism

You can carry out Polymorphism in Java by way of two totally different strategies:

  1. Method Overloading
  2. Method Overriding

What is Method Overloading in Java?

Method overloading is the method that may create a number of strategies of the identical title in the identical class, and all of the strategies work in numerous methods. Method overloading happens when there may be a couple of methodology of the identical title within the class.

Example of Method Overloading in Java

class Shapes {
  public void space() {
    System.out.println("Find space ");
  }
public void space(int r) {
    System.out.println("Circle space = "+3.14*r*r);
  }

public void space(double b, double h) {
    System.out.println("Triangle space="+0.5*b*h);
  }
public void space(int l, int b) {
    System.out.println("Rectangle space="+l*b);
  }


}

class Main {
  public static void predominant(String[] args) {
    Shapes myShape = new Shapes();  // Create a Shapes object
    
    myShape.space();
    myShape.space(5);
    myShape.space(6.0,1.2);
    myShape.space(6,2);
    
  }
}

Output:

Find space
Circle space = 78.5
Triangle space=3.60
Rectangle space=12

What is Method Overriding in Java?

Method overriding is the method when the subclass or a baby class has the identical methodology as declared within the father or mother class.

Example of Method Overriding in Java

class Vehicle{  
  //defining a technique  
  void run(){System.out.println("Vehicle is transferring");}  
}  
//Creating a baby class  
class Car2 extends Vehicle{  
  //defining the identical methodology as within the father or mother class  
  void run(){System.out.println("automobile is working safely");}  
  
  public static void predominant(String args[]){  
  Car2 obj = new Car2();//creating object  
  obj.run();//calling methodology  
  }  
}  

Output:

Car is working safely

Also, Polymorphism in Java could be categorised into two sorts, i.e:

  1. Static/Compile-Time Polymorphism
  2. Dynamic/Runtime Polymorphism

What is Compile-Time Polymorphism in Java?

Compile Time Polymorphism In Java is often known as Static Polymorphism. Furthermore, the decision to the tactic is resolved at compile-time. Compile-Time polymorphism is achieved via Method Overloading. This sort of polymorphism may also be achieved via Operator Overloading. However, Java doesn’t assist Operator Overloading.

Method Overloading is when a category has a number of strategies with the identical title, however the quantity, sorts, and order of parameters and the return sort of the strategies are totally different. Java permits the person freedom to make use of the identical title for varied capabilities so long as it may well distinguish between them by the sort and variety of parameters. Check out among the essential questions on run time polymorphism in java interview questions.

Example of Compile-Time Polymorphism in Java

We will do addition in Java and perceive the idea of compile time polymorphism utilizing subtract() 

package deal staticPolymorphism; 
public class Addition 
{ 
void sum(int a, int b) 
{ 
int c = a+b; 
System.out.println(“ Addition of two numbers :” +c); } 
void sum(int a, int b, int e) 
{ 
int c = a+b+e; 
System.out.println(“ Addition of three numbers :” +c); } 
public static void predominant(String[] args) 
{ 
Addition obj = new Addition(); 
obj.sum ( 30,90); 
obj.sum(45, 80, 22); 
} 
}

The output of this system can be: 

Sum of two numbers: 120 

Sum of three numbers: 147 

In this program, the sum() methodology overloads with two sorts by way of totally different parameters. 

This is the essential idea of compile-time polymorphism in java the place we will carry out varied operations by utilizing a number of strategies having the identical title.

What is Runtime Polymorphism in Java?

Runtime polymorphism in Java can also be popularly referred to as Dynamic Binding or Dynamic Method Dispatch. In this course of, the decision to an overridden methodology is resolved dynamically at runtime somewhat than at compile-time. You can obtain Runtime polymorphism by way of Method Overriding.

Method Overriding is finished when a baby or a subclass has a technique with the identical title, parameters, and return sort because the father or mother or the superclass; then that perform overrides the perform within the superclass. In less complicated phrases, if the subclass offers its definition to a technique already current within the superclass; then that perform within the base class is alleged to be overridden.

Also, it must be famous that runtime polymorphism can solely be achieved via capabilities and never information members. 

Overriding is finished by utilizing a reference variable of the superclass. The methodology to be referred to as is set primarily based on the thing which is being referred to by the reference variable. This is often known as Upcasting.

Upcasting takes place when the Parent class’s reference variable refers back to the object of the kid class. For instance:

class A{} 
class B extends A{}  
A a=new B(); //upcasting

Examples of Runtime Polymorphism in Java

Example 1:

In this instance, we’re creating one superclass Animal and three subclasses, Herbivores, Carnivores, and Omnivores. Subclasses prolong the superclass and override its eat() methodology. We will name the eat() methodology by the reference variable of Parent class, i.e. Animal class. As it refers back to the base class object and the bottom class methodology overrides the superclass methodology; the bottom class methodology is invoked at runtime. As Java Virtual Machine or the JVM and never the compiler determines methodology invocation, it’s, due to this fact, runtime polymorphism.

class Animal{  
  void eat(){
System.out.println("Animals Eat");
}  
}  
class herbivores extends Animal{  
  void eat(){
System.out.println("Herbivores Eat Plants");
} 
  }
class omnivores extends Animal{  
  void eat(){
System.out.println("Omnivores Eat Plants and meat");
} 
  }
class carnivores extends Animal{  
  void eat(){
System.out.println("Carnivores Eat meat");
} 
  }
class predominant{
  public static void predominant(String args[]){ 
    Animal A = new Animal();
    Animal h = new herbivores(); //upcasting  
	Animal o = new omnivores(); //upcasting  
    Animal c = new carnivores(); //upcasting  
    A.eat();
    h.eat();
    o.eat();  
    c.eat();  
  
  }  
}  

Output:

Animals eat
Herbivores Eat Plants
Omnivores Eat Plants and meat
Carnivores eat meat

Example 2:

In this instance, we’re creating one superclass Hillstations and three subclasses Manali, Mussoorie, Gulmarg. Subclasses prolong the superclass and override its location() and famousfor() methodology. We will name the situation() and famousfor() methodology by the Parent class’, i.e. Hillstations class. As it refers back to the base class object and the bottom class methodology overrides the superclass methodology; the bottom class methodology is invoked at runtime. Also, as Java Virtual Machine or the JVM and never the compiler determines methodology invocation, it’s runtime polymorphism.

class Hillstations{  
  void location(){
System.out.println("Location is:");
}  
void famousfor(){
System.out.println("Famous for:");
}  

}  
class Manali extends Hillstations {  
  void location(){
System.out.println("Manali is in Himachal Pradesh");
}  
void famousfor(){
System.out.println("It is Famous for Hadimba Temple and journey sports activities");
}  
  }
class Mussoorie extends Hillstations {  
  void location(){
System.out.println("Mussoorie is in Uttarakhand");
}  
void famousfor(){
System.out.println("It is Famous for training establishments");
}  
  }
class Gulmarg extends Hillstations {  
  void location(){
System.out.println("Gulmarg is in J&Ok");
}  
void famousfor(){
System.out.println("It is Famous for snowboarding");
}  
  }
class predominant{
  public static void predominant(String args[]){ 
    Hillstations A = new Hillstations();
    Hillstations M = new Manali();

    Hillstations Mu = new Mussoorie();

    Hillstations G = new Gulmarg();

    A.location();
A.famousfor();

M.location();
M.famousfor();

Mu.location();
Mu.famousfor();

G.location();
G.famousfor();
  }  
}  

Output:

Location is:
Famous for:
Manali is in Himachal Pradesh
It is Famous for Hadimba Temple and journey sports activities
Mussoorie is in Uttarakhand
It is Famous for training establishments
Gulmarg is in J&Ok
It is Famous for snowboarding

Example of run-time polymorphism in java

We will create two courses Car and Innova, Innova class will prolong the automobile class and can override its run() methodology.

class Car 
{ 
void run() 
{ 
System.out.println(“ running”); 
} 
}
class innova extends Car 
{ 
void run(); 
{ 
System.out.println(“ running fast at 120km”); 
} 
public static void predominant(String args[]) 
{ 
Car c = new innova(); 
c.run(); 
} 
} 

The output of the next program can be; 

Running quick at 120 km. 

Another instance for run-time polymorphism in Java

Now, allow us to test if we will obtain runtime polymorphism by way of information members. 

class automobile 
{ 
int speedlimit = 125; 
} 
class innova extends automobile 
{ 
int speedlimit = 135; 
public static void predominant(String args[]) 
{ 
automobile obj = new innova(); 
System.out.println(obj.speedlimit);
}

The output of the next program can be : 

125 

This clearly implies we will’t obtain Runtime polymorphism by way of information members. In quick, a technique is overridden, not the info members.

Runtime polymorphism with multilevel inheritance

class grandfather 
{ 
void swim() 
{ 
System.out.println(“ Swimming”); 
} 
} 
class father extends grandfather 
{ 
void swim() 
{ 
System.out.println(“ Swimming in river”); 
} 
} 
class son extends father 
{ 
void swim() 
{ 
System.out.println(“ Swimming in pool”);
} 
public static void predominant(String args[]) 
{ 
grandfather f1,f2,f3; 
f1 =new grandfather(); 
f2 = new father(); 
f3 = new son(); 
f1.swim(); 
f2.swim(); 
f3.swim(): 
} 
} 

The output of the next program can be: 

Swimming, Swimming in river, Swimming in pool

Another runtime polymorphism with multilevel inheritance instance

class soundAnimal 
{ 
public void Sound() 
{ 
System.out.println("Different sounds of animal"); }
} 
class buffalo extends soundAnimal 
{ 
public void Sound() 
{ 
System.out.println("The buffalo sound- gho,gho"); } 
} 
class snake extends soundAnimal 
{ 
public void Sound() 
{ 
System.out.println("The snake sound- his,his"); } 
} 
class tiger extends soundAnimal
{ 
public void Sound() 
{ 
System.out.println("The tiger sounds- roooo, rooo"); } 
} 
public class Animal Main 
{ 
public static void predominant(String[] args) 
{ 
soundAnimal Animal = new soundAnimal(); soundAnimal buffalo = new buffalo(); 
soundAnimal snake = new snake(); 
soundAnimal tiger = new tiger(); 
Animal.Sound(); 
buffalo.Sound();
snake.Sound(); 
tiger.Sound(); 
} 
} 

The output of the next program can be; 

The buffalo sound- gho,gho 

The snake sound- his,his 

The tiger sound- roooo,roooo 

We hope you bought an concept about runtime and compile-time polymorphism.

Polymorphic Subtypes

Subtype principally implies that a subtype can function one other sort’s subtype, sounds a bit difficult? 

Let’s perceive this with the assistance of an instance:

Assuming we’ve to attract some arbitrary shapes, we will introduce a category named ‘shape’ with a draw() methodology. By overriding draw() with different subclasses resembling circle, sq., rectangle, trapezium, and so forth we’ll introduce an array of sort ‘shape’ whose components retailer references will seek advice from ‘shape’ subclass references. Next time, we’ll name draw(), all shapes cases draw () methodology can be referred to as.

This Subtype polymorphism usually depends on upcasting and late binding. A casting the place you forged up the inheritance hierarchy from subtype to a supertype is termed upcasting.

To name non-final occasion strategies we use late binding. In quick, a compiler mustn’t carry out any argument checks, sort checks, methodology calls, and so forth, and go away every part on the runtime. 

What is Polymorphism in Programming?

Polymorphism in programming is outlined utilization of a single image to symbolize a number of differing kinds.

What is Polymorphism Variables?

A polymorphic variable is outlined as a variable that may maintain values of various sorts in the course of the course of execution.

Why use Polymorphism in Java?

Polymorphism in Java makes it potential to write down a technique that may accurately course of a number of several types of functionalities which have the identical title. We can even achieve consistency in our code by utilizing polymorphism.

Advantages of Polymorphism in Java

  1. It offers reusability to the code. The courses which might be written, examined and applied could be reused a number of occasions. Furthermore, it saves loads of time for the coder. Also, the one can change the code with out affecting the unique code.
  2. A single variable can be utilized to retailer a number of information values. The worth of a variable you inherit from the superclass into the subclass could be modified with out altering that variable’s worth within the superclass; or every other subclasses.
  3. With lesser strains of code, it turns into simpler for the programmer to debug the code.

Characteristics of Polymorphism

Polymorphism has many different traits aside from Method Overloading and Method Overriding. They embody:

  • Coercion
  • Internal Operator Overloading
  • Polymorphic Variables or Parameters

1. Coercion

Coercion offers with implicitly changing one sort of object into a brand new object of a unique sort. Also, that is executed mechanically to stop sort errors within the code. 

Programming languages resembling C, java, and so forth assist the conversion of worth from one information sort to a different information sort. Data sort conversions are of two sorts, i.e., implicit and specific. 

Implicit sort conversion is mechanically executed in this system and this kind of conversion can also be termed coercion. 

For instance, if an operand is an integer and one other one is in float, the compiler implicitly converts the integer into float worth to keep away from sort error.

Example:

class coercion {

  public static void predominant(String[] args) {
    Double space = 3.14*5*7;
System.out.println(space);
String s = "pleased";
int x=5;
String phrase = s+x;
System.out.println(phrase);

  }
}

Output:

109.9
happy5

2. Internal Operator Overloading

In Operator Overloading, an operator or image behaves in additional methods than one relying upon the enter context or the kind of operands. It is a attribute of static polymorphism. Although Java doesn’t assist user-defined operator overloading like C++, the place the person can outline how an operator works for various operands, there are few cases the place Java internally overloads operators.

Operator overloading is the idea of utilizing the operator as per your selection. Therefore, an operator image or methodology title can be utilized as a ‘user-defined’ sort as per the necessities. 

For instance, ‘+’ can be utilized to carry out the addition of numbers (similar information sort) or for concatenation of two or extra strings.

In the case of +, can be utilized for addition and in addition for concatenation.

For instance:

class coercion {

  public static void predominant(String[] args) {
    
String s = "pleased";
String s1 = "world";
int x=5;
int y=10;

System.out.println(s+s1);
System.out.println(x+y);

  }
}

Output :

Similarly, operators like! &, and | are additionally within the overload place for logical and bitwise operations. In each of those circumstances, the kind of argument will determine how the operator will interpret.

 3. Polymorphic Variables or Parameters

In Java, the thing or occasion variables symbolize the polymorphic variables. This is as a result of any object variables of a category can have an IS-A relationship with their very own courses and subclasses.

The Polymorphic Variable is a variable that may maintain values of various sorts in the course of the time of execution.

Parametric polymorphism specifies that whereas class declaration, a subject title can affiliate with differing kinds, and a technique title can affiliate with totally different parameters and return sorts.

For instance:

class Shape
{
public void show()
{
System.out.println("A Shape.");
}
}
class Triangle extends Shape
{
public void show()
{
System.out.println("I'm a triangle.");
}
}
class Main{
public static void predominant(String[] args)
{
Shape obj;
obj = new Shape();
obj.show();
obj = new Triangle();
obj.show();
}
}

Output:

A Shape.
I’m a triangle.

Here, the obj object is a polymorphic variable. This is as a result of the superclass’s similar object refers back to the father or mother class (Shape) and the kid class (Triangle). 

Problems with Polymorphism 

With a number of benefits, there are additionally just a few disadvantages of polymorphism.

  • Polymorphism is sort of difficult whereas implementation.
  • It tends to cut back the readability of the code.
  • It raises some severe efficiency points in real-time as nicely.

Type Identification During Downcasting 

Downcasting is termed as casting to a baby sort or casting a standard sort to a person sort.

So, we use downcasting at any time when we have to entry or perceive the behaviour of the subtypes. 

Example, 

This is a hierarchical instance 

Food> Vegetable> Ladyfinger, Tomato 

Here, tomato and ladyfinger are two subclasses. 

In downcasting, we slender the kind of objects, which suggests we’re changing frequent sort to particular person sort. 

Vegetable vegetable = new Tomato(); 

Tomato castedTomato = (Tomato) vegetable; 

Here we’re casting frequent sort to a person sort, superclass to subclass which isn’t potential immediately in java.

We explicitly inform the compiler what the runtime sort of the thing is.

Fragile base class drawback 

Fragile base class drawback is nothing however a elementary architectural drawback. 

Sometimes the improper design of a father or mother class can lead a subclass of a superclass to make use of superclass in some unpredicted methods. 

The fragility of inheritance will result in damaged codes even when all the standards is met. 

This architectural drawback is termed as a fragile base class drawback in object-oriented programming programs and language. 

Basically, the explanation for the delicate base drawback is that the developer of the bottom class has no concept of the subclass design. There isn’t any resolution but for this drawback. 

Conclusion

We hope it’s essential to have gotten a primary concept of polymorphism in Java and the way we use it in addition to issues associated to them. 

Hence, this brings us to the tip of the weblog on Polymorphism in Java. Furthermore, to study extra about programming and different associated ideas, try the programs on Great Learning Academy and PG Programs in Software Engineering.  

Also, in case you are getting ready for Interviews, try these Interview Questions for Java to ace it like a professional.

So, don’t cease your journey of studying. Also, don’t overlook to upskill and reskill your self. Keep exploring and continue to learn.

Frequently Asked Questions

What is polymorphism with instance?

One of the OOPs options that enables us to hold out a single motion in varied methods is called polymorphism in Java. For instance, we’ve a category Animal with a technique sound(). This is a generic class and so we can’t give it an implementation resembling: Meow, Oink, Roar, and so forth. 

What are the 4 varieties of polymorphism?

The 4 varieties of polymorphism are:
– Runtime or Subtype polymorphism
– Overloading or Parametric polymorphism
– Compile-time or Ad hoc polymorphism
– Casting or Coercion polymorphism

What is polymorphism in OOPs?

One of the core ideas of OOP or object-oriented programming, polymorphism describes conditions by which a particualr factor happens in numerous kinds. In pc science, polymorphism describes an idea that enables us to entry several types of objects via the identical interface.

What is overriding in OOP?

In object-oriented programming, overriding is a characteristic that enables a subclass or baby class to offer a selected implementation of a technique that’s already supplied by one in every of its superclasses or father or mother courses.

What is overriding vs overloading?

If two or extra strategies in the identical class have the identical title, however have totally different parameters, this is called Overloading. In case of Overriding, a technique signature (title and parameters) are present in the identical superclass and the kid class.

Take step one in the direction of reaching your targets by enrolling on this software program engineering course now!!!

LEAVE A REPLY

Please enter your comment!
Please enter your name here