请写出以下程序运行结果:
class Width {
public static final int SINGLE = 1;
}
class Shape {
public void draw(int Width) {
System.out.println("Shape.draw()"+width);
}
}
class Circle extends Shape {
public void draw(Width n) {
System.out.println("Circle.draw()");
}
}
public class Test {
public static void test(Shape s) {
s.draw(Width.Single);
}
public static void main(String[] args) {
Shape c = new Circle();
test(c);
}
}
参考答案如下:
Shape.draw()1
解析:
class Width {
public static final int SINGLE = 1;
}
class Shape {
public void draw(int Width) {
System.out.println("Shape.draw()"+Width);//<3>输出Shape.draw()1
}
}
class Circle extends Shape {
public void draw(Width n) {
System.out.println("Circle.draw()");//<4>
}
}
public class Test {
public static void test(Shape s) {
s.draw(Width.SINGLE);//<2>调用Circle类的draw()方法
}
public static void main(String[] args) {
Shape c = new Circle();
test(c);//<1>调用本类构造方法
}
}
注意程序运行顺序是<1><2><3>而不是<1><2><4>。
为什么<2>调用的draw()方法是<3>的draw()而不是<4>的draw()?原因在于<2>处调用的draw()方法的实参Width.SINGLE,Width.SINGLE为int型,所以要在Circle类中找draw(int Width)而不是draw(Width n)。
<4>处的draw()方法并没有覆写(override)父类(Shape类)中的draw()方法,而是重载(overload)。