Java polymorphism and its types



Suppose that Shape declares a draw() method, its Circle subclass overrides this method, Shape s = new Circle(); has just executed, and the next line specifies s.draw();. Which draw() method is called: Shape‘s draw() method or Circle‘s draw() method? The compiler doesn’t know which draw() method to call. All it can do is verify that a method exists in the superclass, and verify that the method call’s arguments list and return type match the superclass’s method declaration. However, the compiler also inserts an instruction into the compiled code that, at runtime, fetches and uses whatever reference is in s to call the correct draw() method. This task is known as late binding.

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.

Latest articles

spot_imgspot_img

Related articles

Leave a reply

Please enter your comment!
Please enter your name here

spot_imgspot_img