search
HomeJavajavaTutorialPolymorphism in Java

Polymorphism is defined as a concept wherein, along with one action in numerous ways, it could be performed. The word was originated from the 2 Greek words, which are poly as well as morphs. Here, as you might know, “poly” implies many, as well as “morphs” implies many forms. Therefore, the word polymorphism would imply many forms. Let us now understand Polymorphism in java in detail.

How does Polymorphism work in Java?

Polymorphism is an OOO programming characteristic. Whenever we use it, a class has got the ability to exhibit many functionalities even if they exhibit the common interface. Therefore, we can assume the long word actually tells a very simple concept.

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

The thing worth noting about polymorphism is that the entire working code in numerous classes does not really need to understand the class that is getting used by it in the same way of usage.

Let us assume the real-world example of polymorphism. Let us assume the button. You all know that if we apply a little bit of pressure, you will be able to press the button; however, we won’t be knowing the output of putting pressure on the button and the purpose of the use. So, the point here to take care of is that either way, the result won’t be affecting the procedure that is being used.

So the basic goal of Polymorphism is to make objects which are interchangeable depending on the needs.

Types of Polymorphism in Java

  • The two types of polymorphism are compile-time polymorphism and run-time polymorphism. Compile-time polymorphism is performed by method overloading and runtime polymorphism by method overriding.
  • Runtime polymorphism, also called Dynamic Method Dispatch, is a process wherein a call to an overridden method is resolved at runtime despite at compile-time. Herein, the overridden method is called through a reference variable of a parent class. Also, Runtime polymorphism cannot be achieved by data members.

Importance

If we discard dynamic polymorphism as well as static polymorphism, in programming exists some of the programming characteristics of Java which exhibits polymorphism that is other than these two important types.

They are these – Coercion, Operator Overloading, and Polymorphic Parameters.

1. Coercion

Let’s try to get the meaning of coercion through this example. Assume there exists the value of the string to be co value: Assume the second number that has got the value 2. Now, what would occur when you will concat this string value along with this number? The outcome that we get out of this concatenation would be “co value: 2”. This is known as Coercion. This is a conversion that is of type implicit, which is executed to prevent errors.

2. Operator Overloading

As we start with the concept of operator overloading, let me glance at one scenario. Assume the string has got the value “Operate” and 2nd that has got value as “Overload”. Then we would utilize plus symbol (+) along the same way the addition of 2 numbers. This (+) would be concatenating. If we consider two integers, then adding these two numbers would be returned. Whenever one symbol or operator has the ability to alter the interpretation considering the procedure used, the polymorphism type that gets done is known as Operator Overloading.

3. Polymorphic Parameters

It means allowing access to any object in any of these below ways given as under –

  • Usage of a reference variable that belongs to either parent class.
  • Usage of a reference variable that belongs to the class where that exists.

4. Polymorphism Scope

Binding means the connection of a method call to a method body. There exist two kinds of binding:

  • 1st is Static binding which means whenever the type of object has been determined during compile-time.
  • 2nd is Dynamic binding which means whenever the type of object has been determined during run-time.

The sole reason as to why Polymorphism is required lies as its concept is enormously needed in the implementation of inheritance. It also plays a vital role in allowing the objects to inherit numerous structures in sharing the interface. Polymorphism has been mentioned clearly as the only one that is mapped for many.

Examples of Polymorphism in Java

Given below are the different examples of Polymorphism in Java:

Example #1

Java program to showcase Method Overloading.

Code:

class methodOverload {
static int multi(int x, int y)
{
return x * y;
}
// Method with the same name but with 2 double arguments
static double multi(double x, double y)
{
return x * y;
}
}
class Main {
public static void main(String[] args)
{
System.out.println(methodOverload.multi(6, 2));
System.out.println(methodOverload.multi(1.2, 1.2));
}
}

Output:

Polymorphism in Java

Example #2

Java program to showcase Operator Overloading.

Code:

class operator {
void oper(String s, String s2)
{
String s = s + s2;
System.out.println("Concatenated String is"
+ s);
}
void oper(int a, int b)
{
int c = a + b;
System.out.println("Sum is : " + c);
}
}
class Main {
public static void main(String[] args)
{
operator o = new operator();
o.oper(1, 2);
o.oper("hi", "bye");
}
}

Output:

Polymorphism in Java

Example #3

Java program for Method Overloading.

Code:

class Multi {
// Method with 2 parameter
static int Multi(int a, int b)
{
return a * b;
}
static int Multi(int a, int b, int c)
{
return a * b * c;
}
}
class Main {
public static void main(String[] args)
{
System.out.println(Multi.Multi(2, 3));
System.out.println(Multi.Multi(2, 3, 3));
}
}

Output:

Polymorphism in Java

Conclusion

The sole reason as to why Polymorphism is required lies as its concept is enormously needed in the implementation of inheritance. It also plays a vital role in allowing the objects to inherit numerous structures in sharing the interface. Polymorphism has been mentioned clearly as the only one that is mapped for many.

The above is the detailed content of Polymorphism in Java. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
JVM performance vs other languagesJVM performance vs other languagesMay 14, 2025 am 12:16 AM

JVM'sperformanceiscompetitivewithotherruntimes,offeringabalanceofspeed,safety,andproductivity.1)JVMusesJITcompilationfordynamicoptimizations.2)C offersnativeperformancebutlacksJVM'ssafetyfeatures.3)Pythonisslowerbuteasiertouse.4)JavaScript'sJITisles

Java Platform Independence: Examples of useJava Platform Independence: Examples of useMay 14, 2025 am 12:14 AM

JavaachievesplatformindependencethroughtheJavaVirtualMachine(JVM),allowingcodetorunonanyplatformwithaJVM.1)Codeiscompiledintobytecode,notmachine-specificcode.2)BytecodeisinterpretedbytheJVM,enablingcross-platformexecution.3)Developersshouldtestacross

JVM Architecture: A Deep Dive into the Java Virtual MachineJVM Architecture: A Deep Dive into the Java Virtual MachineMay 14, 2025 am 12:12 AM

TheJVMisanabstractcomputingmachinecrucialforrunningJavaprogramsduetoitsplatform-independentarchitecture.Itincludes:1)ClassLoaderforloadingclasses,2)RuntimeDataAreafordatastorage,3)ExecutionEnginewithInterpreter,JITCompiler,andGarbageCollectorforbytec

JVM: Is JVM related to the OS?JVM: Is JVM related to the OS?May 14, 2025 am 12:11 AM

JVMhasacloserelationshipwiththeOSasittranslatesJavabytecodeintomachine-specificinstructions,managesmemory,andhandlesgarbagecollection.ThisrelationshipallowsJavatorunonvariousOSenvironments,butitalsopresentschallengeslikedifferentJVMbehaviorsandOS-spe

Java: Write Once, Run Anywhere (WORA) - A Deep Dive into Platform IndependenceJava: Write Once, Run Anywhere (WORA) - A Deep Dive into Platform IndependenceMay 14, 2025 am 12:05 AM

Java implementation "write once, run everywhere" is compiled into bytecode and run on a Java virtual machine (JVM). 1) Write Java code and compile it into bytecode. 2) Bytecode runs on any platform with JVM installed. 3) Use Java native interface (JNI) to handle platform-specific functions. Despite challenges such as JVM consistency and the use of platform-specific libraries, WORA greatly improves development efficiency and deployment flexibility.

Java Platform Independence: Compatibility with different OSJava Platform Independence: Compatibility with different OSMay 13, 2025 am 12:11 AM

JavaachievesplatformindependencethroughtheJavaVirtualMachine(JVM),allowingcodetorunondifferentoperatingsystemswithoutmodification.TheJVMcompilesJavacodeintoplatform-independentbytecode,whichittheninterpretsandexecutesonthespecificOS,abstractingawayOS

What features make java still powerfulWhat features make java still powerfulMay 13, 2025 am 12:05 AM

Javaispowerfulduetoitsplatformindependence,object-orientednature,richstandardlibrary,performancecapabilities,andstrongsecurityfeatures.1)PlatformindependenceallowsapplicationstorunonanydevicesupportingJava.2)Object-orientedprogrammingpromotesmodulara

Top Java Features: A Comprehensive Guide for DevelopersTop Java Features: A Comprehensive Guide for DevelopersMay 13, 2025 am 12:04 AM

The top Java functions include: 1) object-oriented programming, supporting polymorphism, improving code flexibility and maintainability; 2) exception handling mechanism, improving code robustness through try-catch-finally blocks; 3) garbage collection, simplifying memory management; 4) generics, enhancing type safety; 5) ambda expressions and functional programming to make the code more concise and expressive; 6) rich standard libraries, providing optimized data structures and algorithms.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)