What is method overloading? [duplicate]

廉价感情. 提交于 2019-11-30 20:41:18

That's just a very general way of describing it. Method overloading allows you to use a single method name, but "overload it" (provide more than one version) depending on "context" (which is typically the type or number of arguments passed in). Since each method is separate, they can cause a "different outcome".

For example, using C#, you can write:

void Foo()  // Version with no arguments
{
}

void Foo(int arg) // Version with a single int
{
}

void Foo(string arg1, double arg2) // Version with string and double parameters
{
}

First, you should know what is signature in programming. A signature of a function is its representation; the name of a function and its parameters determine its signature.

Overloading means changing the signature of a function to meet our needs.

Have a look at the following example:

int sum(int x, int y, int z) {
    return x + y + z;
}

int sum(int x, int y) {
    return x + y;
}

Now, the function sum() can be called through two different ways: Either you can call it with two arguments or you can call it with three arguments. you have changed its signature to meet your needs. Instead of writing a separate function for two arguments, you put the load on the same function, that is why this is known as overloading.

david99world

It's where you have a multitude of methods of the same name with different parameters.

public void kittens(String paws) {

}

public void kittens(String paws, boolean tail) {

}

Both can be called independently to one another with either

kittens("fat"); 

or

kittens("thin", true);

The context in this case is determined by the argument signature of the method, i.e. the number and type of the arguments.

For example:

methodName(int x, int y, int w, int h)
methodName(Vector x)

The first method implementation would be an alternative to:

methodName(new Vector(x, y, w, h))

Is the ability of some languages to create methods/function with the same name but that differ for input / otput parameters.

A classical example is the class constructor overloading example in Java:

  //Constructor without parameters
  public User() {
  }

 //Constructor with only one parameter
 public User(String username)
 {
 this.username = username;
 }

 //Constructor with two parameters
 public User(String username, int age)
 {
   this.username=username;
   this.age=age;
 }

You have a class with different constructors that accept different parameters, as you see they differ in their signature.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!