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 known as: Form
‘s draw()
technique or Circle
‘s draw()
technique? The compiler doesn’t know which draw()
technique to name. All it could actually 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 right draw()
technique. This activity is named late binding.
I’ve created an utility that demonstrates subtype polymorphism by way of 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
{
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
utility class whose primary()
technique drives the applying.