Saturday, 27 December 2014

Polymorphism and dynamic binding in Java

Structure of the Problem Requirements 

In this problem we will learn the basic concept of OOP like Polymorphism and Dynamic binding. Ploymorphism is the provision of single interface to entities of different types or we can say that polymorphism is the ability of an object to take on many forms. With the help of polymorphism in this code we make different geometric shapes.  Here is the source code of this program which help you in better understanding.

Source Code 

Shape.Java

package LEP.uzair.polymorphism;

public class Shape {
public void draw() {
System.out.println("Shape");
}
}

Square.Java 

package LEP.uzair.polymorphism;

public class Square extends Shape{
public void draw() {
System.out.println("Square");
draw_square();
}
private void draw_square() {
System.out.println("Square Implement here");
}
}

Circle.Java


package LEP.uzair.polymorphism;

public class Circle extends Shape {
public void draw() {
System.out.println("Circle");
draw_circle();
}

private void draw_circle() {
System.out.println("Circle Implement here");
}
}

main.Java


package LEP.uzair.main;

import java.util.Scanner;

import LEP.uzair.polymorphism.Circle;
import LEP.uzair.polymorphism.Shape;
import LEP.uzair.polymorphism.Square;

public class MyMain {

public static void main(String[] args) {
Shape Shape_obj;// For same object different constructors will be used
System.out.println("\nWhat do u want to view\n");
System.out.println("a: Circle\n");
System.out.println("b: Square\n");
System.out.println("c: Shape\n");
System.out.println("You Select : ");
char switchChoice;
Scanner input = new Scanner(System.in);
switchChoice =(input.next()).charAt(0);
switch (switchChoice) 
{
case 'a': {
//Notice Shape_obj is of type shape and Constructor is of type Circle
Shape_obj = new Circle(); //Polymorphism
Shape_obj.draw();//Dynamic Binding Draw of circle will be called
break;
}
case'b': {
//Notice Shape_obj is of type shape and Constructor is of type Square
Shape_obj = new Square();//Polymorphism
Shape_obj.draw();//Dynamic Binding Draw of square will be called
break;
}
case'c': {
//Notice Shape_obj is of type shape and Constructor is of type Square
Shape_obj = new Shape();//Polymorphism
Shape_obj.draw();//Dynamic Binding Draw of shape will be called
break;
}
default: {
System.out.println("Invalid Selection");
break;
}
}
}
}

Output of the Program

Polimorphism in Java
Polimorphism in Java

Share it Please
asad

About Author!

Asad Niazi is Software Engineer , Programmer, Web Developers and a young mentor of Tech Solutions Desk and Blogging Solutions . Asad Love to writes about Technology, Programming, Blogging and make money online.

0 comments:

Post a Comment