Pin It

How to demonstrate Polymorphism through a simple Java program ?.

Program to demonstrate how to implement Polymorphism in Java.

package com.hubberspot.examples;

class Shape {

 public void draw(){

  System.out.println("Shape drawn ... ");

 }

}

class Rectangle extends Shape {

 public void draw(){

  System.out.println("Rectangle drawn ... ");

 }
}

class Circle extends Shape {

 public void draw(){

  System.out.println("Circle drawn ... ");

 }

}

// Polymorphism implementing class 
// Performing decoupling as well
// Later in design if a new shape appears
// the functionality of the class has 
// decoupled the object creation hardcoding 
// to a polymorphic way using setShape() 
// and drawShape()
class Drawing {

 private Shape s;

 // Setting polymorphic behavior and 
 // this class doesnt care which shape
 // it is.
 public void setShape(Shape s) {

  this.s = s;

 }

 public void drawShape() {

  this.s.draw();

 }
}


public class Test {

 public static void main(String[] args) {

  Rectangle rectangle = new Rectangle();
  Circle circle = new Circle();

  Drawing drawing = new Drawing();

  drawing.setShape(rectangle);
  drawing.drawShape();

  drawing.setShape(circle);
  drawing.drawShape();

 }
}



Output of the program :



Please Give Us Your 1 Minute In Sharing This Post!
SOCIALIZE IT →
FOLLOW US →
SHARE IT →
Related Posts Plugin for WordPress, Blogger...

Post your related queries below ...

comments powered by Disqus
Powered by Blogger.
 
© 2012 Learn Java by Examples Template by Hubber Spot