I'm trying to understand the rationale for the last statement of my code being illegal in Java. See comment below.
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
}
}
I know that I shouldn't use this design, and instead use different constructors. I know that getColor()
is "not defined in Rectangle." Still, the way I think about this code is: sameObjectDifferentType is a reference to an object that is both a Rectangle and a ColoredRectangle, and therefore I should be able to access all of its members regardless if I declare the reference as Rectangle or ColoredRectangle. So... why is Java designed like this?