I need to call a Method of a an abstract class implementation. But the compiler always defaults to use the overloaded method from the concrete class, since the signature just requires an inherited type.
Just have a look at the code:
-- This is obviously a vastly simplified version of the actual code that I'm using ;)
public class ModelBase { }
public class ModelA : ModelBase { }
public interface IInterface<in TModel>
{
void Do(TModel model);
}
public abstract class AbstractClass<TModel> : IInterface<TModel>
{
public abstract void Do(TModel model);
}
public class ConcreteClass : AbstractClass<ModelA>, IInterface<ModelBase>
{
public override void Do(ModelA model)
{
// I'd like to invoke this method
}
public void Do(ModelBase model)
{
// how do I invoke the method above??
Do((ModelA)model);
}
}
^^ This results in a recursion
What I've tried is:
((IClass<ModelA>)this).Do((ModelA)model);
^^ doesn't change anything
base.Do((ModelA)model);
^^ throws an error "Cannot call an abstract base member: 'AbstractClass.Do(ModelA)'"
How do I call the "public override void Do(ModelA model)" method?
btw. If I change the class to this
public class ConcreteClass : IInterface<ModelA>, IInterface<ModelBase>
it works.
A subclass must override all abstract methods of an abstract class. However, if the subclass is declared abstract, it's not mandatory to override abstract methods.
The process of compiler trying to resolve the method call from given overloaded method definitions is called overload resolution. If the compiler can not find the exact match it looks for the closest match by using upcasts only (downcasts are never done). As expected the output is 10.
In Java, two or more methods may have the same name if they differ in parameters (different number of parameters, different types of parameters, or both). These methods are called overloaded methods and this feature is called method overloading.
An abstract method is a method that is declared, but contains no implementation. you can override both abstract and normal methods inside an abstract class. only methods declared as final cannot be overridden.
Cast this
to AbstractClass<ModelA>
before call:
public void Do(ModelBase model)
{
((AbstractClass<ModelA>)this).Do((ModelA)model);
}
Use named parameters:
public class ConcreteClass : AbstractClass<ModelA>, IInterface<ModelBase>
{
public override void Do(ModelA modelA) // change 'model' into 'modelA'
{
// I'd like to invoke this method
}
public void Do(ModelBase model)
{
// how do I invoke the method above??
Do(modelA : (ModelA)model);
}
}
Now, the compiler knows that you want to call the Do(ModelA)
method and not the Do(ModelBase)
method.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With