开发者

Cannot call derived class method in a function that takes base class as parameter

I have the following problem:

class A {
   void f() {}
}

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

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

void foo(A temp)  
{
   temp.g();
}

I want my foo() function to take a base class parameter, so I can work with B & C. But inside the funciton I have a call to a derived class method, so of course I get an error.

I also tried this inside the foo function:

if(tem开发者_开发知识库p instanceof B)
{
   B somevar = (B)temp;
}
else if( temp instanceof C)
{
   C someVar = (C)temp;
}

someVar.g();

But still I have a compile errors that it doesnt know who someVar is. How could I make this to work ?

Thanks.


The usual solution is to declare a function in the base class that the derived classes override.


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

You can olnly call the method g() on an instance of B because the method is defined in B. You can declare the g() method as abstract in the base A class. But this will imply that this method also exists in C


You will have to call their respective methods inside the if statement as someVar can only view class A methods (if not typecasted to correct type).


if(temp instanceof B)
{
   ((B)temp).g();
}
else if( temp instanceof C)
{
   ((C)temp).g();
}
else
   return;/throw new Exception();


What about using interfaces?

public interface G {
  void g();
}

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

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

And then...

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


The compileError comes from the fact that variables are scoped to their block in Java. This means that when you write

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

somevar exists only inside the if block.

Use

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜