【问题标题】:Can you initialize a derived class with an instance of a baseclass你能用基类的实例初始化派生类吗
【发布时间】:2015-06-19 02:08:37
【问题描述】:

我的意思是基类,它本身并没有使用派生类的实例进行初始化。即假设它不是一个抽象类。

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;

【问题讨论】:

    标签: java polymorphism derived-class base-class


    【解决方案1】:

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

    Triangle u;
    GeomObj v = (GeomObj)u;
    

    【讨论】:

    • 这就像狗和酒吧:每个酒吧(子类)都是狗(超类),但不是每只狗都是酒吧。 =)
    • 我只是想知道为什么它不能像 int 那样在使用 typecast 时转换为 double ,其中只是使用附加参数创建了一个新对象。并感谢答案:)
    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-19
      • 2022-12-03
      • 1970-01-01
      • 1970-01-01
      • 2021-11-27
      • 1970-01-01
      • 1970-01-01
      • 2020-08-19
      相关资源
      最近更新 更多