我對Java很陌生,遇到了一個奇怪的行爲,我無法解釋爲什麼會發生這種情況,或者我的代碼中的錯誤在哪裏。爲什麼多態性不能像我期望的那樣在我的代碼中工作?
下面的代碼:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
abstract class Shape {
public abstract void printMe(String no);
}
final class Circle extends Shape {
@Override
public void printMe(String no){
System.out.println("This is Circle no: " + no);
}
}
final class Square extends Shape {
@Override
public void printMe(String no) {
System.out.println("This is Square no: " + no);
}
}
final class Triangle extends Shape {
@Override
public void printMe(String no) {
System.out.println("This is Triangle no: " + no);
}
}
public class Foo {
private ArrayList<Shape> shapes;
public Foo(){
this.shapes = new ArrayList<Shape>();
this.shapes.add(new Circle());
this.shapes.add(new Square());
this.shapes.add(new Triangle());
}
public void printShapes(ArrayList<String> numbers){
for(String s:numbers){
Iterator<Shape> iter = this.shapes.iterator();
Shape shape = iter.next();
shape.printMe(s);
}
}
public static void main(String[] args) {
ArrayList<String> numbers = new ArrayList<String>(Arrays.asList("1", "2", "3"));
Foo foo = new Foo();
foo.printShapes(numbers);
}
}
我期望的輸出是:
This is Circle no: 1
This is Square no: 2
This is Triangle no: 3
然而,輸出我得到的是:
This is Circle no: 1
This is Circle no: 2
This is Circle no: 3
我在做什麼錯誤?