Given:
abstract class Shape {
Shape() { System.out.println("Shape"); }
protected void area() { System.out.println("Shape"); }
}
class Square extends Shape {
int side;
Square(int side) {
/* insert code here */
this.side = side;
}
public void area() { System.out.println("Square"); }
}
class Rectangle extends Square {
int len, br;
Rectangle(int x, int y) {
/* insert code here */
len = x; br = y;
}
void area() { System.out.println("Rectangle"); }
}
Which two modifications enable the code to compile?
A. At line 1, remove abstract
B. At line 9, insert super();
C. At line 12, remove public
D. At line 17, insert super(x);
E. At line 17, insert super(); super.side = x;
F. At line 20, use public void area () {
题解
原先题目的程序会在第 16 行和第 20 行编译错误,原因在于 Rectangle 类别的构造器没有指定要先调用哪个构造器,因此会自动加上「super();」去调用 Square 类别没有参数的构造器,但这个构造器并不存在。而 Rectangle 类别中的 area 方法,覆写了 Square 类别中的 area 方法,但是可见度却从 public 降到 default,这是不被允许的。
所以说,选项 D 和选项 F 是正确的。
选项 C 不行的原因在于,Shape 类别的 area 方法之可见度为 protected,所以 Square 类别的 area 方法之可见度必定也不能低于 protected。
