我有以下问题:
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是谁.我怎么能让这个工作?
谢谢.
| 归档时间: |
|
| 查看次数: |
2102 次 |
| 最近记录: |