Free Data Structures and Algorithms Course









Subscribe below and get all best seller courses for free !!!










OR



Subscribe to all free courses

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 :



 
© 2021 Learn Java by Examples Template by Hubberspot