[HTML payload içeriği buraya]
26.7 C
Jakarta
Wednesday, May 6, 2026

Polymorphism in Java with Examples in 2024- Nice Studying


What’s Polymorphism in Java?

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

So, languages that don’t help polymorphism usually are not ‘Object-Oriented Languages’, however ‘Object-Primarily 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 lessons are associated.

Inheritance is a robust 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 completely different duties. Thus, permitting us to realize the identical motion in many alternative methods.

What’s Polymorphism?

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

Should Study Core Java Subjects

Actual-Life Examples of Polymorphism

A person can have completely different relationships with completely different folks. A lady could be a mom, a daughter, a sister, and a pal, all on the identical time, i.e. she performs different behaviors in numerous conditions.

The human physique has completely different organs. Each organ has a special operate to carry out; the guts is chargeable for blood stream, the lungs for respiratory, the mind for cognitive exercise, and the kidneys for excretion. So we have now a normal technique operate that performs otherwise relying upon the organ of the physique. 

Polymorphism in Java Instance

A superclass named “Shapes” has a technique known as “space()”. Subclasses of “Shapes” could be “Triangle”, “circle”, “Rectangle”, and many others. Every subclass has its manner of calculating space. Utilizing Inheritance and Polymorphism means, the subclasses can use the “space()” technique to seek out the realm’s method for that form.

class Shapes {
  public void space() {
    System.out.println("The method 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 Fundamental {
  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 method for the realm of the Triangle is ½ * base * peak
The method for the realm of the Circle is 3.14 * radius * radius

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

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

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

class Fundamental {
    public static void predominant(String[] args) {
        Form s1 = new Circle();
        Form s2 = new Sq.();

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

On this instance, we have now a base class Form with a single technique draw() that prints “Drawing a form” to the console. We then create two subclasses, Circle and Sq., that override the draw() technique to print “Drawing a circle” and “Drawing a sq.” respectively.

Within the predominant technique, we create two situations of the Form class, s1 and s2, which are literally situations of the Circle and Sq. subclasses. After we name the draw() technique on these objects, the right implementation is known as primarily based on the precise kind of the thing, that is run-time polymorphism. This system will output: “Drawing a circle” and “Drawing a sq.”

On this instance, the draw() technique is overridden within the subclasses, and this enables for this system to find out which technique to make use of at runtime. This is called runtime polymorphism or dynamic polymorphism, As a result of at runtime the JVM determines the precise kind of the thing and calls the corresponding technique.

Additionally Learn: OOPs ideas in Java

Forms of Polymorphism

You’ll be able to carry out Polymorphism in Java through two completely different strategies:

  1. Methodology Overloading
  2. Methodology Overriding

What’s Methodology Overloading in Java?

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

Instance of Methodology Overloading in Java

class Shapes {
  public void space() {
    System.out.println("Discover 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 Fundamental {
  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:

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

What’s Methodology Overriding in Java?

Methodology overriding is the method when the subclass or a baby class has the identical technique as declared within the mum or dad class.

Instance of Methodology Overriding in Java

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

Output:

Automobile is operating safely

Additionally, Polymorphism in Java could be categorized into two sorts, i.e:

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

What’s Compile-Time Polymorphism in Java?

Compile Time Polymorphism In Java is also referred to as Static Polymorphism. Moreover, the decision to the strategy is resolved at compile-time. Compile-Time polymorphism is achieved by way of Methodology Overloading. The sort of polymorphism may also be achieved by way of Operator Overloading. Nonetheless, Java doesn’t help Operator Overloading.

Methodology Overloading is when a category has a number of strategies with the identical identify, however the quantity, sorts, and order of parameters and the return kind of the strategies are completely different. Java permits the person freedom to make use of the identical identify for numerous capabilities so long as it may well distinguish between them by the sort and variety of parameters. Try a few of the essential questions on run time polymorphism in java interview questions.

Instance of Compile-Time Polymorphism in Java

We are going to 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 will probably be: 

Sum of two numbers: 120 

Sum of three numbers: 147 

On this program, the sum() technique overloads with two sorts through completely different parameters. 

That is the essential idea of compile-time polymorphism in java the place we are able to carry out numerous operations by utilizing a number of strategies having the identical identify.

What’s Runtime Polymorphism in Java?

Runtime polymorphism in Java can also be popularly often called Dynamic Binding or Dynamic Methodology Dispatch. On this course of, the decision to an overridden technique is resolved dynamically at runtime somewhat than at compile-time. You’ll be able to obtain Runtime polymorphism through Methodology Overriding.

Methodology Overriding is completed when a baby or a subclass has a technique with the identical identify, parameters, and return kind because the mum or dad or the superclass; then that operate overrides the operate within the superclass. In easier phrases, if the subclass supplies its definition to a technique already current within the superclass; then that operate within the base class is claimed to be overridden.

Additionally, it must be famous that runtime polymorphism can solely be achieved by way of capabilities and never knowledge members. 

Overriding is completed by utilizing a reference variable of the superclass. The strategy to be known as is set primarily based on the thing which is being referred to by the reference variable. That is also referred to as Upcasting.

Upcasting takes place when the Guardian 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

Instance 1:

On this instance, we’re creating one superclass Animal and three subclasses, Herbivores, Carnivores, and Omnivores. Subclasses lengthen the superclass and override its eat() technique. We are going to name the eat() technique by the reference variable of Guardian class, i.e. Animal class. Because it refers back to the base class object and the bottom class technique overrides the superclass technique; the bottom class technique is invoked at runtime. As Java Digital Machine or the JVM and never the compiler determines technique 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 Crops");
} 
  }
class omnivores extends Animal{  
  void eat(){
System.out.println("Omnivores Eat Crops 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 Crops
Omnivores Eat Crops and meat
Carnivores eat meat

Instance 2:

On this instance, we’re creating one superclass Hillstations and three subclasses Manali, Mussoorie, Gulmarg. Subclasses lengthen the superclass and override its location() and famousfor() technique. We are going to name the placement() and famousfor() technique by the Guardian class’, i.e. Hillstations class. Because it refers back to the base class object and the bottom class technique overrides the superclass technique; the bottom class technique is invoked at runtime. Additionally, as Java Digital Machine or the JVM and never the compiler determines technique invocation, it’s runtime polymorphism.

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

}  
class Manali extends Hillstations {  
  void location(){
System.out.println("Manali is in Himachal Pradesh");
}  
void famousfor(){
System.out.println("It's Well-known 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's Well-known for schooling establishments");
}  
  }
class Gulmarg extends Hillstations {  
  void location(){
System.out.println("Gulmarg is in J&Ok");
}  
void famousfor(){
System.out.println("It's Well-known 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:
Well-known for:
Manali is in Himachal Pradesh
It’s Well-known for Hadimba Temple and journey sports activities
Mussoorie is in Uttarakhand
It’s Well-known for schooling establishments
Gulmarg is in J&Ok
It’s Well-known for snowboarding

Instance of run-time polymorphism in java

We are going to create two lessons Automobile and Innova, Innova class will lengthen the automobile class and can override its run() technique.

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

The output of the next program will probably be; 

Working quick at 120 km. 

One other instance for run-time polymorphism in Java

Now, allow us to verify if we are able to obtain runtime polymorphism through knowledge 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 will probably be : 

125 

This clearly implies we are able to’t obtain Runtime polymorphism through knowledge members. In brief, 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 will probably be: 

Swimming, Swimming in river, Swimming in pool

One other runtime polymorphism with multilevel inheritance instance

class soundAnimal 
{ 
public void Sound() 
{ 
System.out.println("Totally 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 Fundamental 
{ 
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 will probably be; 

The buffalo sound- gho,gho 

The snake sound- his,his 

The tiger sound- roooo,roooo 

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

Polymorphic Subtypes

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

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

Assuming we have now to attract some arbitrary shapes, we are able to introduce a category named ‘form’ with a draw() technique. By overriding draw() with different subclasses corresponding to circle, sq., rectangle, trapezium, and many others we’ll introduce an array of kind ‘form’ whose components retailer references will consult with ‘form’ subclass references. Subsequent time, we’ll name draw(), all shapes situations draw () technique will probably be known as.

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

To name non-final occasion strategies we use late binding. In brief, a compiler shouldn’t carry out any argument checks, kind checks, technique calls, and many others, and depart the whole lot on the runtime. 

What’s Polymorphism in Programming?

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

What’s Polymorphism Variables?

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

Why use Polymorphism in Java?

Polymorphism in Java makes it potential to put in writing a technique that may accurately course of a lot of various kinds of functionalities which have the identical identify. We will additionally acquire consistency in our code by utilizing polymorphism.

Benefits of Polymorphism in Java

  1. It supplies reusability to the code. The lessons which might be written, examined and applied could be reused a number of instances. Moreover, it saves a whole lot of time for the coder. Additionally, the one can change the code with out affecting the unique code.
  2. A single variable can be utilized to retailer a number of knowledge 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 another subclasses.
  3. With lesser strains of code, it turns into simpler for the programmer to debug the code.

Traits of Polymorphism

Polymorphism has many different traits aside from Methodology Overloading and Methodology Overriding. They embrace:

  • Coercion
  • Inner Operator Overloading
  • Polymorphic Variables or Parameters

1. Coercion

Coercion offers with implicitly changing one kind of object into a brand new object of a special form. Additionally, that is completed routinely to stop kind errors within the code. 

Programming languages corresponding to C, java, and many others help the conversion of worth from one knowledge kind to a different knowledge kind. Knowledge kind conversions are of two sorts, i.e., implicit and express. 

Implicit kind conversion is routinely completed 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 kind error.

Instance:

class coercion {

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

  }
}

Output:

109.9
happy5

2. Inner 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’s a attribute of static polymorphism. Though Java doesn’t help user-defined operator overloading like C++, the place the person can outline how an operator works for various operands, there are few situations the place Java internally overloads operators.

Operator overloading is the idea of utilizing the operator as per your alternative. Due to this fact, an operator image or technique identify can be utilized as a ‘user-defined’ kind as per the necessities. 

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

Within the case of +, can be utilized for addition and likewise for concatenation.

For instance:

class coercion {

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

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

  }
}

Output :

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

 3. Polymorphic Variables or Parameters

In Java, the thing or occasion variables symbolize the polymorphic variables. It’s because any object variables of a category can have an IS-A relationship with their very own lessons and subclasses.

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

Parametric polymorphism specifies that whereas class declaration, a subject identify can affiliate with differing types, and a technique identify can affiliate with completely different parameters and return sorts.

For instance:

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

Output:

A Form.
I’m a triangle.

Right here, the obj object is a polymorphic variable. It’s because the superclass’s identical object refers back to the mum or dad class (Form) and the kid class (Triangle). 

Issues with Polymorphism 

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

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

Sort Identification Throughout Downcasting 

Downcasting is termed as casting to a baby kind or casting a typical kind to a person kind.

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

Instance, 

It is a hierarchical instance 

Meals> Vegetable> Ladyfinger, Tomato 

Right here, tomato and ladyfinger are two subclasses. 

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

Vegetable vegetable = new Tomato(); 

Tomato castedTomato = (Tomato) vegetable; 

Right here we’re casting frequent kind to a person kind, superclass to subclass which isn’t potential immediately in java.

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

Fragile base class drawback 

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

Typically the improper design of a mum or dad 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 factors is met. 

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

Mainly, the explanation for the delicate base drawback is that the developer of the bottom class has no thought of the subclass design. There is no such thing as a resolution but for this drawback. 

Conclusion

We hope you need to have gotten a fundamental thought of polymorphism in Java and the way we use it in addition to issues associated to them. 

Therefore, this brings us to the top of the weblog on Polymorphism in Java. Moreover, to study extra about programming and different associated ideas, take a look at the programs on Nice Studying Academy and PG Packages in Software program Engineering.  

Additionally, in case you are getting ready for Interviews, take a look at these Interview Questions for Java to ace it like a professional.

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

Steadily Requested Questions

What’s polymorphism with instance?

One of many OOPs options that permits us to hold out a single motion in numerous methods is called polymorphism in Java. For instance, we have now a category Animal with a technique sound(). It is a generic class and so we can not give it an implementation corresponding to: Meow, Oink, Roar, and many others. 

What are the 4 kinds of polymorphism?

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

What’s polymorphism in OOPs?

One of many core ideas of OOP or object-oriented programming, polymorphism describes conditions through which a particualr factor happens in numerous varieties. In pc science, polymorphism describes an idea that permits us to entry various kinds of objects by way of the identical interface.

What’s overriding in OOP?

In object-oriented programming, overriding is a characteristic that permits a subclass or youngster class to offer a selected implementation of a technique that’s already offered by certainly one of its superclasses or mum or dad lessons.

What’s overriding vs overloading?

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

Partaking within the research of Java programming suggests a eager curiosity within the realm of software program growth. For these embarking upon this journey with aspirations in the direction of a profession on this subject, it is suggested to discover the next pages so as to purchase a complete understanding of the event profession path:

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Latest Articles