Ok, I'm trying to do the following:
protected bool ValidAdvert(Base item)
{
throw ThisIsAnAbstractClassException();
}
protected bool ValidAdvert(Derived1 item)
{
return ADerived1SpecificPredicate;
}
protected bool ValidAdvert(Derived2 item)
{
return ADerived2SpecificPredicate;
}
And have the Derived class versions of the method be called, when a Base class is passed to the method. The base class is abstract so this should, in theory, be possible?
Before someone says something about overloading the method on the classes themselves, the logic inside the methods relies on a large number of different conditions, none of which are related, and none of which related to the Base/Derived class directly (such as login status, etc.)
Since the constructors can't be defined in derived class, it can't be overloaded too, in derived class.
Example 3: Accessing Overridden Function Inside the Derived Class. The overridden function of the base class can also be accessed by the derived class using the scope resolution operator (::). In this way, you can also access the overridden function by the instance of the derived class.
Yes it is overloading , This overloading is happening in case of the class ' C ' which is extending P and hence having two methods with the same nam e but different parameters leading to overloading of method hello() in Class C .
Yes of course, overloading in inheritance class is possible in Java. Java compiler detect that add method has multiple implementations. so according to the parameter java compiler will determines which method has to be executed. class Parent { public void add(int a) { System.
If you find the double dispatch too intrusive, you can call the method by reflection and resolve the proper overload dynamically.
protected bool ValidAdvert(Base item)
{
if (item.GetType() == typeof(Base))
throw new ThisIsAnAbstractClassException();
Type type = typeof(CurrentClass);
MethodInfo method = type.GetMethod("ValidAdvert",
BindingFlags.Instance | BindingFlags.NonPublic,
null,
new Type[] { item.GetType() },
null);
return (bool)method.Invoke(this, new object[] { item });
}
protected bool ValidAdvert(Derived1 item)
{
return ADerived1SpecificPredicate;
}
protected bool ValidAdvert(Derived2 item)
{
return ADerived2SpecificPredicate;
}
This pattern is called MultipleDispatch, while calling a method by reflection is slower than calling the method directly (it won't be an overhead if the method is called less than few hundred times per second), it has the benefit of not requiring to modify your class hierarchy like in the Double Dispatch pattern.
This will be even easier when c# 4.0 comes out with the dynamic keyword:
protected bool ValidAdvert(Base item)
{
if (item.GetType() == typeof(Base))
throw new ThisIsAnAbstractClassException();
dynamic dynamicThis = this;
return (bool)dynamicThis.ValidAdvert(item as dynamic);
}
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