Above shown code sample is an example of method overriding.
this is the way by which java implements runtime polymorphism.
In java if an overriden method is called using superclass refernce, java determines which version of that method to execute depending upon the type of object being referred to
at the time of call, not depending on the type of variable.
consider
class Figure{
double dim1;
double dim2;
Figure(double dim1,double dim2){
this.dim1=dim1;
this.dim2=dim2;
}
double area(){
return 0;
}
}
class Rectangle extends Figure{
Rectangle(double dim1,double dim2){
super(dim1,dim2);
}
double area(){
double a;
a=dim1*dim2;
System.out.println("dimensions of rectangle are "+dim1+" "+dim2);
return a;
}
}
class Triangle extends Figure{
Triangle(double dim1,double dim2){
super(dim1,dim2);
}
double area(){
double a=(dim1*dim2)/2;
System.out.println("base & altitude of triangle are "+dim1+" "+dim2);
return a;
}
}
class test{
public static void main(String[] args){
Figure r;
Rectangle b=new Rectangle(10,10);
Triangle c=new Triangle(10,10);
r=b;
System.out.println("area of rectangle fig "+r.area());
r=c;
System.out.println("area of triangle fig "+r.area());
}
}
output:
dimensions of rectangle are 10.0 10.0
area of rectangle fig 100.0
base & altitude of triangle are 10.0 10.0
area of triangle fig 50.0
for 2nd qstn: no. signature means unique. return type is not a part of signature