Concept of Polymorphism in Java by using Switch logic
Polymorphism means the object which as many forms.It is one of the feature of OOPs . With Polymorphism it is possible to design and implement system that are more easily extensible.
For example:- Suppose the rectangle has four side like quadrilateral ,squares,Parallelogram, and Trapezoid so the rectangle has many form which as four side but it doesn't same as rectangle. It perform the same operation just like rectangle .
With polymorphism , the programmer can deal with the scope concern itself with specifics .The programmer can command a wide variety of objects to deal with proper manner appropriate to those object without even knowing the type of those objects.
class Rectangle{
int getArea(){return 0;}
}
class Parallelogram extends Rectangle{
int getArea(){return 4;}
}
class Trapezoid extends Rectangle{
int getArea(){return 8;}
}
class Square extends Rectangle{
int getArea(){return 12;}
}
public class TestPolymorphism{
public static void main(String args[]){
Rectangle b;
b=new Parallelogram();
System.out.println("Parallelogram has:" +b.getArea());
b=new Trapezoid();
System.out.println("Trapezoid : "+b.getArea());
b=new Square();
System.out.println("Square: "+b.getArea());
}
}
Output
Parallelogram has:4
Trapezoid : 8
Square: 12
Polymorphism using Switch Logic
Problem switch logic:- There are many problem with using switch logic. The programmer might loose to make such a type test when one is warranted.The programmer may forget to test all the possible-cases in switch. If -switch based system is improved by adding new types , the programmer might forget to insert the new cases in existing switch statements. Every addition or deletion of a class demands that every switch statement in the system be modified; tracking these down can be time consuming and error prone.
Polymorphism is an effective alternative to using switch Logic. Polymorphic programming can remove the need for switch logic. The programmer can use java's polymorphism network to perform the equal logic automatically , thus avoiding the kinds of error including with switch logic.