Java polymorphism and its sorts

[ad_1]

Suppose that Form declares a draw() technique, its Circle subclass overrides this technique, Form s = new Circle(); has simply executed, and the following line specifies s.draw();. Which draw() technique is named: Form‘s draw() technique or Circle‘s draw() technique? The compiler doesn’t know which draw() technique to name. All it will possibly do is confirm {that a} technique exists within the superclass, and confirm that the tactic name’s arguments listing and return kind match the superclass’s technique declaration. Nonetheless, the compiler additionally inserts an instruction into the compiled code that, at runtime, fetches and makes use of no matter reference is in s to name the proper draw() technique. This process is called late binding.

I’ve created an utility that demonstrates subtype polymorphism when it comes to upcasting and late binding. This utility consists of Form, Circle, Rectangle, and Shapes courses, the place every class is saved in its personal supply file. Itemizing 1 presents the primary three courses.

Itemizing 1. Declaring a hierarchy of shapes

class Form
{
   void draw()
   {
   }
}

class Circle extends Form
{
   non-public 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
{
   non-public 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 utility class whose most important() technique drives the appliance.

[ad_2]

Leave a Reply

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