简体   繁体   English

为什么多态性不能像我期望的那样起作用?

[英]Why polymorphism does not work as I'd expect in my code?

I'm quite new to Java and have come accross to a strange behaviour that I can not explain why this happens or where is the mistake in my code. 我对Java还是很陌生,遇到了一种奇怪的行为,我无法解释为什么会发生这种情况,或者代码中的错误在哪里。

Here's the code: 这是代码:

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);
    }
}

The output I'd expect would be: 我期望的输出将是:

This is Circle no: 1
This is Square no: 2
This is Triangle no: 3

However, the output I get is: 但是,我得到的输出是:

This is Circle no: 1
This is Circle no: 2
This is Circle no: 3

What am I doing wrong? 我究竟做错了什么?

将此行拉出循环:

 Iterator<Shape> iter = this.shapes.iterator();

You're always getting a new iterator--instead of using the same one. 您总是得到一个新的迭代器-而不是使用相同的迭代器。

It's not clear to me why you're doing it like this anyway; 我不清楚我为什么仍然要这样做。 either pass an integer and loop until it runs out, or iterate over the shapes and keep a counter. 要么传递一个整数并循环直到它用完,要么遍历这些形状并保留一个计数器。 Passing a string array strikes me as clumsy. 传递字符串数组使我感到笨拙。

public void printShapes() {
    int i = 1;
    for (Shape shape : shapes) {
        shape.printMe(i++); // And modify the method to take an int.
    }
}

I'm uncomfortable with a shape needing to be aware it can have a position. 我不满意形状需要知道的位置。 If this is a requirement, create a "PositionalShape" or something (but ew), or have shapes output a string representation that can be composited with additional info like a list position, or create a shape decorator, etc. 如果需要,请创建“ PositionalShape”之类的东西(但是ew),或者让形状输出可以与其他信息(例如列表位置)组合的字符串表示形式,或者创建形状装饰器等。


// (If you're really trying to print the first n shapes)
public void printShapes(int n) {
    Iterator<Shape> iter = shapes.iterator();
    for (int i = 0; i < n; i++) {
        Shape shape = iter.next();
        shape.printMe("" + i+1);
    }
}

Look at Iterator<Shape> iter inside your loop. 查看循环内的 Iterator<Shape> iter

  public void printShapes(ArrayList<String> numbers){
        for(String s:numbers){
            Iterator<Shape> iter = this.shapes.iterator();
            Shape shape = iter.next();
            shape.printMe(s);
        }
    }

You are always grabbing the first shape (initialize iterator, grab next) 您总是在抓住第一个形状(初始化迭代器,然后抓住)

I suspect you need to see this in your debugger however with 我怀疑你需要在调试器中看到这个

Iterator<Shape> iter = this.shapes.iterator();
Shape shape = iter.next();
shape.printMe(s);

You are using the first share every time (which is a Circle) 您每次都使用第一个共享(这是一个圈子)

You can move the iter declaration outside the loop to fix it. 您可以将iter声明移到循环外进行修复。

The following 2 lines need to be in a loop: Shape shape = iter.next(); shape.printMe(s); 以下两行必须处于循环状态: Shape shape = iter.next(); shape.printMe(s); Shape shape = iter.next(); shape.printMe(s);

您总是重置迭代器:

Iterator<Shape> iter = this.shapes.iterator();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM