Java Method overloading

Source: Internet
Author: User
Tags square root

Java Method overloading

"Introduction Definition"

In Java, 2 or more than 2 methods in the same class can have the same name, as long as their argument declarations are different. In this case, the method is called overloading (overloaded), a process called method overloading. Method overloading is a way of implementing polymorphism in Java. If you've never used a language that allows method overloading before, this concept might be a bit strange at first. But you'll see that method overloading is one of the most exciting and useful features of Java.

"parameter type description"

When an overloaded method is called, Java uses the type and (or) number of parameters to indicate the version of the overloaded method that is actually called. Therefore, the type and/or number of arguments for each overloaded method must be different. Although each overloaded method can have a different return type, the return type is not sufficient to distinguish which method is being used. When Java calls an overloaded method, the method that matches the argument to the calling parameter is executed.

"Example explanation and analysis"

Here is a simple example that illustrates the method overload:

Demonstrate method overloading.
Class Overloaddemo {
void Test () {
System.out.println ("No parameters");
}

Overload test for one integerparameter.
void Test (int a) {
System.out.println ("A:" + a);
}

Overload test for the integerparameters. void Test (int a,int b) {System.out.println ("a andb:" + A + "" + b);}

Overload test for a double parameter

Double Test (double a) {

System.out.println ("Double A:" + a);

return a*a; }}

Class Overload {

public static void Main (stringargs[]) {
Overloaddemo ob = new Overloaddemo ();
Double result;

Call all versions oftest () Ob.test (); ob.test; ob.test (10,20); result =ob.test (123.25); System.out.println ("Result of Ob.test (123.25):" +result);

}
}

The program produces the following output:

No parameters

A:10
A and B:10 20
Double a:123.25
Result of Ob.test (123.25): 15190.5625

As seen from the above program, test () is overloaded four times. The first version has no parameters, the second version has an integer parameter, the third version has two integer parameters, and the fourth version has a double type parameter. Because the overloads are not affected by the return type of the method, test () version fourth also returns a value that has no causal relationship with the overload.

When an overloaded method is called, Java looks for a match between the arguments of the calling method and the argument of the method. However, this match is not always accurate. In some cases, the automatic type conversion of Java also applies to the arguments of overloaded methods. For example, look at the following program:

Automatic type conversions Apply tooverloading.
Class Overloaddemo {
void Test () {
System.out.println ("No parameters");
}

Overload test for the integerparameters. void Test (int a,int b) {System.out.println ("a andb:" + A + "" + b);}

Overload test for a double parameter
void Test (double a) {
System.out.println ("Inside test (Double) A:" + a);
}
}

Class Overload {

public static void Main (String args[]) {
Overloaddemo ob = new Overloaddemo ();
int i = 88;

Ob.test (); Ob.test (10,20);
Ob.test (i); This would invoke test (double)
Ob.test (123.2); This would invoke test (double)
}
}

The program produces the following output:

No parameters
A and B:10 20
Inside test (double) a:88
Inside test (double) a:123.2

In this case, the version of Overloaddemo does not have a test (int) defined. Therefore, when you call Test () with an integer parameter in overload, you cannot find a method that matches it. However, Java can automatically convert integers to double type, which can solve this problem. Therefore, after the test (int) is not found, Java expands I to type double and then calls Test (double). Of course, if test (int) is defined, of course, test (int) is called First, and test (double) is not called. The automatic conversion of Java will only work if no exact match is found.

Method overloading supports polymorphism because it is a way for Java to implement the "one interface, multiple methods" paradigm. To understand this, consider this passage: in languages that do not support method overloading, each method must have a unique name. However, you often want to implement methods that have different data types but are essentially the same. You can refer to an example of an absolute value function. In languages that do not support overloading, it usually contains three and more than three versions of the function, each with a slightly different name. For example, in the C language, the function abs () returns the absolute value of an integer, and labs () returns the absolute value () of the Long Integer, and fabs () returns the absolute values of the floating-point. Although the functions of these three functions are essentially the same, because the C language does not support overloading, each function must have its own name. This makes the conceptual situation much more complex. Although the underlying concept of each function is the same, you still have to remember these three names. This is not the case in Java, because all absolute values can use the same name. Indeed, Java's standard class library contains an absolute value method called ABS (). This method is overloaded with the math class of Java to handle numeric types. Java determines the version of the called ABS () based on the parameter type.

The value of overloading is that it allows related methods to be accessed using the same name. Therefore, the name ABS represents the general action it performs. Choosing the correct specified (specific) version for a particular environment is what the compiler will do. As a programmer, you just have to remember that the common operation is done. With the application of polymorphism, several names are reduced to one. Although this example is fairly simple, if you extend the concept, you will understand that overloading can help you solve more complex problems.

When you reload a method, each version of the method can perform any action you want. There are no rules that require that overloaded methods must be interconnected. However, in style, method overloading implies a relationship. This is what you should not do when you are able to use the same name overload independent method. For example, you can use the name Sqr to create a method that returns the square of an integer and the square root of a floating-point value. However, the two operations are functionally different. Applying the method in this way violates its original purpose. In the actual programming, you should only overload the closely related operations.

"Constructor overloading"
In addition to overloading normal methods, constructors can also be overloaded. In fact, for most of the realities you create,

Classes, overloaded constructors are common and are not exceptions. To understand why this is the case, let us recall the example of the box class that was cited in the previous chapter. Here is an example of the latest version of the box class:

Class Box {double width; doubleheight; double depth;

The constructor for Box.

Box (double w,double h,double d) {width = w; height = h;depth= D;

}

Compute and return volume Doublevolume () {return width * height * depth;}}

In this case, the box () constructor requires three arguments, which means that all defined box objects must pass three parameters to the box () constructor. For example, the following statement is not valid in the current situation:

Box OB = new box ();

Because box () requires three parameters, it is an error if you call it without a parameter. This can lead to some important problems. If you only want a box and don't care (or know) its original size what to do or if you want to initialize a cube with just one value, and that value can be used as all three dimensions of it then what to do if the box class is written as it is now, other problems like this you have no way to solve, Because you can only take three parameters and have no other option.

Fortunately, the solution to these problems is fairly easy: overload the box constructor so that it can handle the situation just described. The following program is an improved version of box, which uses the overload of the box constructor to solve these problems:

/* Here,box defines three constructors toinitialize

The dimensions of a box various ways.
*/
Class Box {

Double width; Double height; doubledepth; constructor used when all dimensions specified Box (double w,double h,double D) {

width = w;
Height = h;
depth = D;

}

Constructor used when no dimensionsspecified Box () {width =-1;//use-1 to indicate
Height =-1; An uninitialized
depth =-1; Box
}

Constructor used when Cube iscreated Box (double len) {width = height = depth = len;}

Compute and return volume Doublevolume () {return width * height * depth;}}

Class Overloadcons {

public static void Main (String args[]) {//Create boxes using the various constructorsbox mybox1 = new Box (10,20,15); Box Mybox2 = new box (); Box mycube =new Box (7);

Double Vol;

Get volume of first box
vol = mybox1.volume ();
System.out.println ("Volume of Mybox1 is" + vol);

}
}

The output generated by the program is as follows:

Volume of Mybox1 is 3000.0
Volume of Mybox2 is-1.0
Volume of Mycube is 343.0

Java Method overloading

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.