Java:接口(interface)

标签 java class interface casting

我一直在阅读有关java中的接口(interface)的内容。总的来说,除了一个问题之外,我理解了这个概念。在 http://goo.gl/l5r69 (docs.oracle),在注释中写道,我们可以对接口(interface)和实现它的类进行类型转换。那就是

public interface Relatable { 
    public int isLargerThan (Relatable other) ; 
} 

public class RectanglePlus implements Relatable { 
    public int width = 0; 
    public int height = 0; 
    public Point origin; 

    // four constructors 
    // ...

    // a method for computing the area of the rectangle 
    public int getArea() { 
        return width * height; 
    } 

    // a method required to implement the Relatable interface 
    public int isLargerThan(Relatable other) { 
        RectanglePlus otherRect = (RectanglePlus) other; 

        if (this.getArea() < otherRect.getArea()) { 
            return -1; 
        } else if (this.getArea () > otherRect.getArea()) { 
            return 1; 
        } else {
            return 0;
        }
    } 
}

如何将 otherRect(这是一个接口(interface))转换为 RectanglePlus。令人困惑的是, RectanglePlus 是一个具有变量的,这些变量不存在于另一个接口(interface)

最佳答案

我不得不承认,您展示的 java 文档中的示例非常糟糕且令人困惑。 这很糟糕,因为它包含向下层次结构进行不安全的强制转换。 向上强制转换(从实现类到接口(interface)/父类(super class))始终是安全的,但应尽可能避免向下强制转换。

理想情况下,Relatable 接口(interface)还应包含 getArea() 方法:

public interface Relatable { 
    public int isLargerThan(Relatable other);
    public int getArea();
}

现在您不需要丑陋的 Actor 阵容,只需:

public int isLargerThan(Relatable other) { 
    if (this.getArea() < other.getArea()) { 
        return -1; 
    } else if (this.getArea () > other.getArea()) { 
        return 1; 
    } else {
        return 0;
    }
}

就够了。我还认为 isLargerThan(Relatable other) 是一个坏名字(更大是指什么?)。它可能应该类似于 hasBiggerArea(Relatable other) ,以便它解释我们实际比较的内容(只有“更大”才相当流行)。

关于Java:接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24802425/

相关文章:

java - JMockit 在单元测试中保持不变

java applet ClassNotFoundException 与代码库

javascript - Typescript:基于类创建接口(interface)

c# - 为什么接口(interface)不能指定静态方法?

c# - 解决多接口(interface)实现

java - 错误 405 : Method not Allowed on DELETE and PUT

Java 通用使用格式

php - CodeIgniter:My_Lang 中的 get_instance

python - 具有 Python C 扩展的类(不是方法)的完整和最小示例?

c# - 自定义集合实现 IEnumerable