上面显示的代码示例是方法覆盖的示例。这是java实现运行时多态的方式。在 java 中,如果使用超类引用调用被覆盖的方法,java 会根据调用时引用的对象的类型而不是变量的类型来确定要执行该方法的哪个版本。考虑
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());
}
}
输出:矩形的尺寸为 10.0 10.0 矩形图 100.0 的面积 三角形的底和高度为 10.0 10.0 三角形的面积 50.0
对于第二个 qstn:不。签名意味着独一无二。返回类型不是签名的一部分