Java polymorphism and its sorts

I’ve created an software that demonstrates subtype polymorphism by way of upcasting and late binding. This software consists of Form, Circle, Rectangle, and Shapes lessons, the place every class is saved in its personal supply file. Itemizing 1 presents the primary three lessons.

Itemizing 1. Declaring a hierarchy of shapes

class Form
{
   void draw()
   {
   }
}

class Circle extends Form
{
   personal 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() strategies.

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

class Rectangle extends Form
{
   personal 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()
   // strategies.

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

Itemizing 2 presents the Shapes software class whose predominant() technique drives the applying.

Itemizing 2. Upcasting and late binding in subtype polymorphism

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

The declaration of the shapes array demonstrates upcasting. The Circle and Rectangle references are saved in shapes[0] and shapes[1] and are upcast to sort Form. Every of shapes[0] and shapes[1] is considered a Form occasion: shapes[0] isn’t considered a Circle; shapes[1] isn’t considered a Rectangle.

Leave a Reply

Your email address will not be published. Required fields are marked *