DEV Community

Hayes vincent
Hayes vincent

Posted on

Polymorphism in java

Polymorphism in Java is one of the main aspects of Object-Oriented Programming(OOP). The word polymorphism can be broken down into Poly and morphs, as “Poly” means many and “Morphs” means forms. In simple words, we can say that the ability of a message to be represented in many forms.

Polymorphism is considered one of the important features of Object-Oriented Programming. Polymorphism allows us to perform a single action in different ways. In other words, polymorphism allows you to define one interface and have multiple implementations.

There are two main types of polymorphism in Java
- Method overloading
- Method overriding

** Method overloading**

Within class two or more methods having same method name but different parameter

Method overloading involves defining multiple methods within the same class that share the same name but have different parameter lists (different number of parameters, different data types of parameters, or different order of parameters).

The compiler determines which overloaded method to call based on the arguments provided during the method invocation.

class Methodover{
    int GetInfo(int a,int b){
    return a+b;
}
    int GetInfo(int a,int b,int c){
    return a+b+c;
}

public static void main (String args[]){
    Methodover obj=new Methodover();
    System.out.println("Total:" +obj.GetInfo(2,5));
    //System.out.println("Total:" +obj.GetInfo(2,5,5));//
}
Enter fullscreen mode Exit fullscreen mode

Output:

Method overriding

Aross two class with inheritance both parent and child class having same method singnature then child class class method will overriding the parameter class

Method overriding occurs when a subclass provides its own specific implementation of a method that is already defined in its superclass

The method to be executed is determined at runtime based on the actual object type, not the reference type. This is often demonstrated using a superclass reference variable holding an object of a subclass.

class  Vehicals{

    int GetCar(int a,int b,int c){
    return a+b+c;    
}
public static void main(String args[]){
}
}



class Cars extends Vehicle{
    int GetCar(int a,int b,int c){
    return a+b+c;    
}
public static void main(String args[]){
    Cars obj=new Cars();
    System.out.println("Total:" +obj.GetCar(2,3,4));
    }
}
Enter fullscreen mode Exit fullscreen mode

Output:

Rerferance: https://www.google.com/search?client=firefox-b-lm&q=what+is+polymorphism+in+java

Top comments (0)