16 C
London
Thursday, September 5, 2024

Java polymorphism and its sorts



Suppose that Form declares a draw() technique, its Circle subclass overrides this technique, Form s = new Circle(); has simply executed, and the subsequent line specifies s.draw();. Which draw() technique is known as: Form‘s draw() technique or Circle‘s draw() technique? The compiler doesn’t know which draw() technique to name. All it may well do is confirm {that a} technique exists within the superclass, and confirm that the strategy name’s arguments listing and return sort 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 right draw() technique. This job is called late binding.

I’ve created an software that demonstrates subtype polymorphism when it comes to 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
{
   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 software class whose principal() technique drives the applying.

Latest news
Related news

LEAVE A REPLY

Please enter your comment!
Please enter your name here