您可以使用基类的实例初始化派生类

时间:2015-04-13 16:54:59

标签: java polymorphism derived-class base-class

我指的是一个基类,它本身不是使用派生类的实例初始化的。即,假设它不是抽象类。

class GeomObj{
  Colour x;
}

class Triangle extends GeomObj{
  largestAngle y;
}

GeomObj u;

//now is the following allowed?Taking into account that u was not initialized using an instance of Triangle in the first place

Triangle v = (Triangle)u;

2 个答案:

答案 0 :(得分:2)

不,因为GeomObj不是三角形。但反过来的工作:

Triangle u;
GeomObj v = (GeomObj)u;

答案 1 :(得分:0)

此外,你可以说每个Triangle都是GeomObj,但不是每个GeomObj都是三角形。所以编译器不允许你这样做。