不能在以基类为参数的函数中调用派生类方法

Adr*_*ian 2 java

我有以下问题:

class A {
   void f() {}
}

class B extends A {   
   void g() {}
}

class C extends A {
   void h() {}
}

void foo(A temp)  
{
   temp.g();
}
Run Code Online (Sandbox Code Playgroud)

我希望我的foo()函数采用基类参数,所以我可以使用B&C.但是在函数内部我调用派生类方法,所以当然我得到一个错误.
我也在foo函数中尝试过这个:

if(temp instanceof B)
{
   B somevar = (B)temp;
}
else if( temp instanceof C)
{
   C someVar = (C)temp;
}

someVar.g();
Run Code Online (Sandbox Code Playgroud)

但是我仍然有一个编译错误,它不知道someVar是谁.我怎么能让这个工作?

谢谢.

Mar*_*tos 9

通常的解决方案是在基类中声明派生类重写的函数.