下面代码的第//Line 1和//Line 2行将调用哪个类的方法? ( )
class Rectangle {
double width, length;
Rectangle(double width, double length) {
this.width = width;
this.length = length;
}
double getArea() {
double area = width * length;
return area;
}
void show() {
System.out.println("The width and length are: " + width + ", " + length);
System.out.println("The area is: " + getArea());
}
}
class Square extends Rectangle {
double width, length;
Square(double width) {
super(width, width);
this.width = width;
}
double getArea() {
double area = width * width;
return area;
}
void show() {
System.out.println("The width is: " + width);
System.out.println("The area is: " + getArea());
}
public static void main(String[] args) {
Rectangle shape1 = new Rectangle(5, 2);
Rectangle shape2 = new Square(5);
shape1.show(); // Line 1
shape2.show(); // Line 2
}
}shape1.show(); // Line 1 - Rectangle Class Method Call
shape2.show(); // Line 2 - Square Class Method Call
shape1.show(); // Line 1 - Square Class Method Call
shape2.show(); // Line 2 -Square Class Method Call
shape1.show(); // Line 1 - Rectangle Class Method Call
shape2.show(); // Line 2 - Rectangle Class Method Call
代码会在运行时出错。
类多态的典型实现