Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

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(temp 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.

like image 345
Adrian Avatar asked Jul 19 '26 09:07

Adrian


2 Answers

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

like image 165
Marcelo Cantos Avatar answered Jul 20 '26 23:07

Marcelo Cantos


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

like image 25
Manuel Selva Avatar answered Jul 20 '26 21:07

Manuel Selva



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!