JAVA method Overloading

Source: Internet
Author: User
JAVA method overloading-general Linux technology-Linux programming and kernel information. The following is a detailed description. In Java, two or more methods in the same class can have the same name, as long as their parameter declarations are different. In this case, this method is called overloaded. This process is called method overloading ). Method Overloading is a way to implement polymorphism in Java. If you have never used a language that allows method overloading before, this concept may be a bit strange at first. But you will see that method Overloading is one of the most exciting and useful features of Java.

When an overloaded method is called, Java uses the parameter type and (or) quantity to indicate the version of the actually called overloaded method. Therefore, the parameter types and (or) quantities of each overload method must be different. Although each overload method can have different return types, the return types are not enough to distinguish which method is used. When Java calls an overloaded method, the method that matches the called parameter is executed.

The following is a simple example of method overloading:

// Demonstrate method overloading.
Class OverloadDemo {
Void test (){
System. out. println ("No parameters ");
}

// Overload test for one integer parameter.
Void test (int ){
System. out. println ("a:" + );
}

// Overload test for two integer parameters. void test (int a, int B) {System. out. println ("a and B:" + a + "" + B );}

// Overload test for a double parameter

Double test (double ){

System. out. println ("double a:" + );

Return a * ;}}

Class Overload {

Public static void main (String args []) {
OverloadDemo ob = new OverloadDemo ();
Double result;

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

}
}

The program generates 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 shown in the preceding procedure, test () is reloaded 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 parameter. Since the overload is not affected by the return type of the method, the fourth version of test () also returns a value that has no causal relationship with the overload.

When an overloaded method is called, Java finds a match between the parameters of the method to call and the independent variables of the method. However, such matching is not always accurate. In some cases, Java's automatic type conversion also applies to the independent variables of the overloaded method. For example, look at the following program:

// Automatic type conversions apply to overloading.
Class OverloadDemo {
Void test (){
System. out. println ("No parameters ");
}

// Overload test for two integer parameters. void test (int a, int B) {System. out. println ("a and B:" + a + "" + B );}

// Overload test for a double parameter
Void test (double ){
System. out. println ("Inside test (double) 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 will invoke test (double)
Ob. test (123.2); // this will invoke test (double)
}
}

The program generates the following output:

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

In this example, this version of OverloadDemo does not define test (int ). Therefore, if you call test () with an integer in Overload, no matching method can be found. However, Java can automatically convert Integers to the double type, which can solve this problem. Therefore, after test (int) cannot be found, Java expands I to the double type and calls test (double ). Of course, if test (int) is defined, test (int) is called first instead of test (double ). Java's automatic conversion takes effect only when no exact match is found.

Method overloading supports polymorphism because it is a method that implements the "one interface, multiple methods" pattern in Java. To understand this, consider the following: in languages that do not support method overloading, each method must have a unique name. However, you often want to implement different but essentially the same methods for different data types. You can refer to the example of absolute value function. In languages that do not support overloading, there are usually three or more versions of this function. Each version has a name with little difference. For example, in C language, the abs () function returns the absolute value of an integer, labs () returns the absolute value of a long integer (), and fabs () returns the absolute value of a floating point value. 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 concept much more complex. Although each function has the same potential concept, you still have to remember these three names. This will not happen in Java, because all absolute value functions can use the same name. Indeed, Java's standard class library contains an absolute value method called abs (). This method is overloaded by the math class of Java and used to process numeric types. Java decides the version of abs () called Based on the parameter type.

The value of overload is that it allows relevant methods to be accessed using the same name. Therefore, the abs name represents the general action it performs ). Selecting the correct specific version for a specific environment is what the compiler should do. As a programmer, you only need to remember the general operations you perform. By applying polymorphism, several names are reduced to one. Although this example is quite simple, if you extend this concept, you will understand that overloading can help you solve more complex problems.

When you reload a method, each version of the method can execute any action you want. There is no requirement that overload methods must be associated with each other. However, method overloading implies a link. This is what you should not do when you can use the same name to reload irrelevant methods. For example, you can use sqr to create a method that returns the sum of squares of an integer and the square root of a floating point value. However, these two operations have different functions. Using this method violates its original intention. In actual programming, you should only reload closely related operations.

7.1.1 constructors overload
In addition to normal methods, constructors can also be overloaded. In fact, most of

Class, overload constructor is very common, not any exception. To understand why this is the case, let's look back at the Box class example mentioned in the previous chapter. The following is an example of the Box class in the latest version:

Class Box {double width; double height; double depth;

// This is the constructor for Box.

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

}

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

In this example, the Box () constructor requires three independent variables, which means that all the defined Box objects must pass three parameters to the Box () constructor. For example, the following statement is invalid in the current situation:

Box ob = new Box ();

Box () requires three parameters. Therefore, it is an error to call without parameters. This will cause some important problems. What if you only want a box and don't care (or know) its original size? Or, what if you want to use only one value to initialize a cube and the value can be used as all three dimensions of it? If the Box class is written like this, you cannot solve other problems like this, because you can only include three parameters without any other options.

Fortunately, the solution to these problems is quite easy: Reload the Box constructor so that it can handle the situation just described. The following Program is an improved version of Box. It uses the overload of Box constructor to solve these problems:

/* Here, Box defines three constructors to initialize

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

Double width; double height; double depth; // constructor used when all dimensions specified Box (double w, double h, double d ){

Width = w;
Height = h;
Depth = d;

}

// Constructor used when no dimensions specified Box () {width =-1; // use-1 to indicate
Height =-1; // an uninitialized
Depth =-1; // box
}

// Constructor used when cube is created Box (double len) {width = height = depth = len ;}

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

Class OverloadCons {

Public static void main (String args []) {// create boxes using the varous 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 );

// Get volume of second box
Vol = mybox2.volume ();
System. out. println ("Volume of mybox2 is" + vol );
// Get volume of cube
Vol = mycube. volume ();
System. out. println ("Volume of mycube is" + vol );

}
}

The output of this program is as follows:

Volume of mybox1 is 3000.0
Volume of mybox2 is-1.0
Volume of mycube is 343.0

In this example, when new is executed, an appropriate constructor is called Based on the specified independent variable.
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.