Polymorphism in Java

Polymorphism refers to a feature of Java that allows an object of a superclass to refer to an object of any subclass. This is possible because all objects of a base class are also objects of its superclass. 

For example, assume that all circles are represented by a class called Circle, which is a subclass of the class Shape (which thus is the superclass of Circle). Further assume that Triangle is another subclass of Shape. Now assume that Shape has a method draw(). You can implement these classes in such a way that when you invoke the draw() method on a Shape variable (referring to an object of Triangle), it draws a triangle, and when you invoke the same method on the same Shape variable (which now is referring to an object of Circle), it draws a circle. It is the same method of the Shape class with different implementations in the subclasses.


DrawShape.java



abstract class Shape {    

       abstract void draw();
}

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

class Triangle extends Shape {
       void draw() {
              System.out.println("Triangle drawn.");
       }
}

public class DrawShape {
       public static void main(String[] args) {
              Shape shape1 = new Circle();
              Shape shape2 = new Triangle();
              shape1.draw();
              shape2.draw();
       }
}


 

2 comments: