• Fri. Nov 29th, 2024

Java polymorphism and its types

Byadmin

Aug 20, 2024



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.

Late binding vs early binding
Late binding is used for calls to non-final instance methods. For all other method calls, the compiler knows which method to call. It inserts an instruction into the compiled code that calls the method associated with the variable’s type and not its value. This technique is known as early 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.



Source link