class Shape {
void draw() {}
void erase() {}
void print() {
System.out.println( "Base-class print() ");
}
}
class Circle extends Shape {
void draw() {
System.out.println( "Circle.draw() ");
}
void erase() {
System.out.println( "Circle.erase() ");
}
void print() {
System.out.println( "Circle.print() ");
}
}
class Square extends Shape {
void draw() {
System.out.println( "Square.draw() ");
}
void erase() {
System.out.println( "Square.erase() ");
}
void print() {
System.out.println( "Square.print() ");
}
}
class Triangle extends Shape {
void draw() {
System.out.println( "Triangle.draw() ");
}
void erase() {
System.out.println( "Triangle.erase() ");
}
void print() {
System.out.println( "Triangle.print() ");
}
}
public class E01_NewShapeMethod {
public static void main(String args[]) {
Shape[] s = {
new Circle(), new Square(), new Triangle(),
};
// Make polymorphic method calls:
for(int i = 0; i < s.length; i++) {
s[i].draw();
s[i].erase();
s[i].print();
}
}
} ///:~
正确的运行结果:
Circle.draw()
Circle.erase()
Circle.print()
Square.draw()
Square.erase()
Square.print()
Triangle.draw()
Triangle.erase()
Triangle.print()
1.这个结果不是这样??:
Circle.draw()
Circle.erase()
Base-class print()
Square.draw()
Square.erase()
Base-class print()
Triangle.draw()
Triangle.erase()
Base-class print()
------解决方案--------------------
父类的方法被重写了
这个时候你调用的一定是子类的方法
------解决方案--------------------
父类里面的方法全部被覆写了,你又用调用的子类的方法,所以不显示Base-class print(),而显示对应子类的print方法