Applying Method Overriding
Let's see at a more practical instance which uses methods overriding. This subsequent program creates a superclass called Figure which stores the dimensions of several 2D objects. The class also defines a method called area ( ) which computes the area of an object. The given program derives two subclasses from Figure. The first is rectangle and the second it Triangle. Every of these subclasses overrides area ( ) so that it returns the area of a rectangle a triangle, correspondingly.
/ / using run time polymorphism.
Class figure {
Double dim 1 ;
Double dim2;
Figure (double a, double b ) {
Dim1 = a;
Dim2 = b;
}
double area ( ) {
System.out.println ("Area for figure is undefined,");
return 0;
}
}
class Rectangle extends Figure
{
rectangle (double a , double b )
{
super ( a, b) ;
}
/ / override area for rectangle double area ( ) {
System.out.println( "Inside Area for Rectangle.");
return dim1 * dim2;
}
}
class triangle extends figure {
Triangle (double a , double b ) {
super (a, b);
/ / override area for right triangle double area ( ) {
System.out.println("inside area for triangle.");
Return dim1*dim2/2;
}
}
class Find Areas {
public static void main (string args [ ]) {
Figure f = new Figure (10,10);
rectangle r = new rectangle ( 8, 9 );
triangle T = new Triangle (10, 8 );
Figure figref;
figref = r;
System.out.println ("Area" + figref.area ( ));
figref = t;
System.out.println.("Area" + figref.area ( ) );
figref = f;
System.out.println ("Area" + figref.area ( ));
The output from the program is display here:
Inside Area for Rectangle.
Area is 45
Inside Area for Triangle.
Are is 40
Area for Figure is undefined.
Area is 0
By the dual mechanisms of inheritance and run time polymorphism that is possible to describe one consistent interface which is used by various different, still associated types of objects. Within case, its area can be obtained through called area ( ) if an object is derived from figure. The interface to this operation is the similar no matter what type of figure is being used.