基类设置为派生类,不能在派生类中调用方法?

use*_*ser 0 c# java oop object

对于不支持从多个类继承的语言,这是一个普遍的OOP问题(不确定这里是否重要,只是认为我已经将这些细节放入其中),如Java:

好的,你有你的基类:

class Base {}

class Derived extends Base
{
   SomeMethod(){}
}

Main()
{
    Base baseInstance = new Base();
    Derived derivedInstance = new Derived();

    baseInstance = derivedInstance;

    baseInstance.someMethod();            <<<<<< this does not work. why?

}
Run Code Online (Sandbox Code Playgroud)

为什么在将baseInstance设置为derivedInstance时,是否无法调用Derived类中定义的方法?

由于您将baseInstance设置为derivedInstance,您是否应该访问此方法?

Mar*_*ell 6

键入为基类的变量不能假定有关子类的方法.例如,对于所有编译器都知道,baseInstance可以保持对a Base或a的引用SomeOtherClass extends Base.现在,你可以说在这种情况下编译器可以解决它,但是:这不是编译器的作用.编译器的规则很简单:如果你有一个类型的变量Base,你只能使用已知的东西Base.

如果你想使用来自特定子类的专门方法,那么你需要让编译器执行带有类型检查的强制转换,即

Derived special = (Derived)baseInstance; // I'm using C# syntax here,
special.someMethod();                    // but should be similar or identical
Run Code Online (Sandbox Code Playgroud)