【发布时间】:2019-06-07 06:26:22
【问题描述】:
我试图了解我的代码的最后一条语句在 Java 中是非法的原因。请参阅下面的评论。
public class Rectangle {
private int height;
private int width;
public Rectangle(int height, int width) {
this.height = height;
this.width = width;
}
}
class ColoredRectangle extends Rectangle {
private String color;
public ColoredRectangle(int height, int width, String color) {
super(height, width);
this.color = color;
}
public String getColor() {
return color;
}
public static void main(String[] args) {
ColoredRectangle blueRectangle = new ColoredRectangle(2, 4, "blue");
Rectangle sameObjectDifferentType = blueRectangle;
((ColoredRectangle) sameObjectDifferentType).getColor(); //Will compile
sameObjectDifferentType.getColor(); //Won't compile
}
}
我知道我不应该使用这种设计,而是使用不同的构造函数。我知道getColor() 是“未在矩形中定义的”。尽管如此,我对这段代码的看法是:sameObjectDifferentType 是对一个既是 Rectangle 又是 ColoredRectangle 对象的引用,因此无论我将引用声明为 Rectangle 还是 ColoredRectangle,我都应该能够访问它的所有成员。那么……为什么 Java 会这样设计?
【问题讨论】:
-
color = this.color应该是this.color = color。 -
我知道 getColor() 是“未在 Rectangle 中定义的。” 这完全正确。
getColor()未在Rectangle中定义。你一开始就想对了。 -
如果你有另一个类是
Rectangle并且有一个getColor()方法会发生什么?现在我们甚至不能输入检查这个表达式。 -
Java 会如何设计?这就是 OOP 的工作原理 - 并非所有
Rectangles 也是ColoredRectangles。 -
Rectangle的构造函数是倒退的,顺便说一句:它从成员变量更新其参数!
标签: java inheritance subclass superclass