using System;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
var a = new Derived();
int x = 123;
a.Foo(x);
}
}
public class Base
{
public virtual void Foo(int x)
{
Console.WriteLine("Base::Foo");
}
}
public class Derived : Base
{
public override void Foo(int x)
{
Console.WriteLine("Derived::Foo(int x)");
}
public void Foo(object o)
{
Console.WriteLine("Derived::Foo(object o)");
}
}
}
Result: "Derived::Foo(object o)"
WHY???
A method is a set of code which is referred to by name and can be called (invoked) at any point in a program simply by utilizing the method's name. Think of a method as a subprogram that acts on data and often returns a value. Each method has its own name.
Method CallsA method is a routine that applies to a particular class of objects. Once an object is declared, you can refer to it by its identifier when calling methods. The following example calls the SetActive method on the Find dialog box: Find.SetActive ()
In languages such as C++, functions are bits of code that will perform a particular action - but are not associated with an object. functions that are to do with an object are called methods. in java all functions are methods as they are all to do with objects.
A method is a block of code which only runs when it is called. You can pass data, known as parameters, into a method. Methods are used to perform certain actions, and they are also known as functions.
When the compiler tries to find candidate method signatures in preparation for overloading, it looks at the most derived type first, and removes overridden methods looking only at "freshly declared" signatures in that class.
If it finds an applicable method, it doesn't go any further up the inheritance chain to find other signatures. This is counterintuitive (at least counter to my intuition) in this sort of situation. It's designed to avoid the "brittle base class" problem, where changing the base class affects other code in unexpected ways - but when the method is actually overridden in the derived class, I can't see the benefit. (Admittedly ignoring that would mean seemingly-no-op methods which override a method just to call the base implementation weren't nearly as safely-removable as you might expect.)
I have a fairly long article going into overloading in a certain amount of detail about this situation and other corner cases - you may find it useful. See section 7.5.3 of the C# specification for more details.
Bottom line: be careful with overloading, particularly across inheritance boundaries.
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