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

Java 无法在以基类为参数的函数中调用派生类方法,java,Java,我有以下问题: class A { void f() {} } class B extends A { void g() {} } class C extends A { void h() {} } void foo(A temp) { temp.g(); } 我希望我的foo()函数接受一个基类参数,这样我就可以使用B&C。但是在这个函数中,我调用了一个派生类方法,所以我当然会得到一个错误。 我也在foo函数中尝试了这一点: if(temp insta

我有以下问题:

class A {
   void f() {}
}

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

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

void foo(A temp)  
{
   temp.g();
}
我希望我的foo()函数接受一个基类参数,这样我就可以使用B&C。但是在这个函数中,我调用了一个派生类方法,所以我当然会得到一个错误。
我也在foo函数中尝试了这一点:

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

someVar.g();
但我仍然有一个编译错误,它不知道someVar是谁。我怎样才能让它工作呢

谢谢

if(temp instanceof B)
{
   B somevar = (B)temp;
   somevar.g();
}

您只能对B的实例调用方法g(),因为该方法是在B中定义的。您可以在基类A中将g()方法声明为抽象方法。但这将意味着此方法也存在于C中。通常的解决方案是在基类中声明派生类覆盖的函数。

您必须在
if
语句中调用它们各自的方法,因为
someVar
只能查看类
a
方法(如果未按正确类型进行类型转换)编译错误源于这样一个事实:在Java中,变量的作用域是其块。这意味着当你写作时

if(temp instanceof B)
{
   B somevar = (B)temp;
}
somevar仅存在于if块内

使用


使用接口怎么样

public interface G {
  void g();
}

class B extends A implements G {
  @Override void g() {
  }
}

class C extends A implements G {
  @Override void g() {
  }
}
然后

void foo(G temp) {
  temp.g();
}
public interface G {
  void g();
}

class B extends A implements G {
  @Override void g() {
  }
}

class C extends A implements G {
  @Override void g() {
  }
}
void foo(G temp) {
  temp.g();
}