Java polymorphism and example What is polymorphism?

 

 Java polymorphism and example

What is polymorphism?

ü  Polymorphism is considered one of the important features of OOPs, polymorphism allows is perform a single action in different ways.

Poly means many | morphisms means form  --many forms (polymorphism)

Real-world  example:-  watersolid, gas, liquid

Type of polymorphism: --

1.       Compile time/overloading/ static polymorphism

2.       Runtime/overriding/ dynamic polymorphism,

Example :

class   Overloading    {

void show(int a , int  b)   {
System.out.println(“intone”);

}

 void show(float a, float  b)  {

System.out.println(“intone”);

}
}

class   Test  {

public static void main(String   args[])   {

Overloading    obj =  new   Overloading  ();

obj.show(12,86);

obj.show(54.88f, 1.88f);

}

}

Special cases of method overloading:--

Q.1can we achieve method overloading by changing the return type of method only?

Ø  In the java method overloading is not possible by changing the return type of the method only because of ambiguity.

Example:-

class   Overloading    {

void show(int a)   {
System.out.println(“intone”);

}

 String show(int a)  {

System.out.println(“inttwo”);

}
}

class   Test  {

public static void main(String   args[])   {

Test  obj =  new   Test  ();

obj.show(86);

}

}

Q.2 can we overload the java main()  method?

Ø  Yes, we can have any number of the main methods in a class by method overloading.

§  This is because JVM always calls main()  method which receives String Array as arguments only.

Example:-

class   Test  {

public static void main(String   args[])   {

System.out.println(“intone”);

Test  obj =  new   Test  ();

obj.show(86);

}

public static void main(int  a)   {

System.out.println(“intone”);

}

}

 

 


 

 

Post a Comment

0 Comments