Polymorphism in Java



Polymorphism in Java is a concept through which we can do a single function in different ways. Polymorphism comes from 2 Greek words: poly and morphs The word "poly" means many and "morphs" forms mean. So polymorphism means many forms.

Java has two types of polymorphism: compile time polymorphism and runtime polymorphism. We can demonstrate polymorphism in Java by method overload and method override.

A reference variable can refer to any object of any subtype of its declared type or its declared type. A reference variable can be declared as a class or interface type.

Polymorphism can be achieved in two of the following ways:
  • Method Overloading(Compile time Polymorphism)
  • Method Overriding(Run time Polymorphism)

Method Overloading

Compile time polymorphism refers to a process in which an overloaded method is resolved over time at compile time instead of the call. Method overloading is an example of timing polymorphism. Law overloading is a feature that allows a class to have two or more methods with the same name, but the logic passed by the methods is different.

Example - 

class Adder {
Static int add(int a, int b)
{
return a+b;
}
static double add( double a, double b)
{
return a+b;
}
 
public static void main(String args[])
{
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(12.3,12.6));
}
}

Method Overriding
Runtime Polymorphism or Dynamic Method Dispatch is a process in which an override method is resolved at runtime instead of compiled-time calls.

Syntax - 

class A{}  
class B extends A{}  .

Example - 

public Class BowlerClass{
void bowlingMethod()
{
System.out.println(" bowler ");
}
public Class FastPacer{
void bowlingMethod()
{
System.out.println(" fast bowler ");
}
Public static void main(String[] args)
{
FastPacer obj= new FastPacer();
obj.bowlingMethod();
}
}
Share on Google Plus

About It E Research

This is a short description in the author block about the author. You edit it by entering text in the "Biographical Info" field in the user admin panel.
    Blogger Comment
    Facebook Comment

0 comments:

Post a Comment