reCAPTCHA WAF Session Token
Information Technology

Java polymorphism and its types


Thank you for reading this post, don't forget to subscribe!

I’ve created an application that demonstrates subtype polymorphism in terms of upcasting and late binding. This application consists of Shape, Circle, Rectangle, and Shapes classes, where each class is stored in its own source file. Listing 1 presents the first three classes.

Listing 1. Declaring a hierarchy of shapes

class Shape
{
   void draw()
   {
   }
}

class Circle extends Shape
{
   private int x, y, r;

   Circle(int x, int y, int r)
   {
      this.x = x;
      this.y = y;
      this.r = r;
   }

   // For brevity, I've omitted getX(), getY(), and getRadius() methods.

   @Override
   void draw()
   {
      System.out.println("Drawing circle (" + x + ", "+ y + ", " + r + ")");
   }
}

class Rectangle extends Shape
{
   private int x, y, w, h;

   Rectangle(int x, int y, int w, int h)
   {
      this.x = x;
      this.y = y;
      this.w = w;
      this.h = h;
   }

   // For brevity, I've omitted getX(), getY(), getWidth(), and getHeight()
   // methods.

   @Override
   void draw()
   {
      System.out.println("Drawing rectangle (" + x + ", "+ y + ", " + w + "," +
                         h + ")");
   }
}

Listing 2 presents the Shapes application class whose main() method drives the application.

Listing 2. Upcasting and late binding in subtype polymorphism

class Shapes
{
   public static void main(String[] args)
   {
      Shape[] shapes = { new Circle(10, 20, 30),
                         new Rectangle(20, 30, 40, 50) };
      for (int i = 0; i < shapes.length; i++)
         shapes[i].draw();
   }
}

The declaration of the shapes array demonstrates upcasting. The Circle and Rectangle references are stored in shapes[0] and shapes[1] and are upcast to type Shape. Each of shapes[0] and shapes[1] is regarded as a Shape instance: shapes[0] isn’t regarded as a Circle; shapes[1] isn’t regarded as a Rectangle.

Back to top button
Consent Preferences
WP Twitter Auto Publish Powered By : XYZScripts.com
SiteLock