Java-4.2 method Overloading
In this section, let's talk about method overloading.
1. Why do I need to overload methods?
In java, there is only one constructor, so if I need to create objects in multiple ways, what should I do? In this case, method Overloading is required. Because the full name of the constructor is called the constructor function, it is a special method. Therefore, we can use method overloading for it, method Overloading is the same for all methods.
Example:
package com.ray.testobject;public class Test {public static void main(String[] args) {}}class TestClass {public TestClass() {}public TestClass(String param) {}}
The code above shows that we need two different methods to create TestClass, So we reload the constructor.
The common methods are the same. The example code below is the transformation of the above Code.
package com.ray.testobject;public class Test {private void info() {}private void info(String id) {}public static void main(String[] args) {}}class TestClass {public TestClass() {}public TestClass(String param) {}}
2. Identify overload Methods
2.1 different parameter locations
package com.ray.testobject;public class Test {private void info(int id, String name) {}private void info(String name, int id) {}public static void main(String[] args) {}}
This method can be reloaded, but is not recommended because of its poor readability, difficulty in maintenance, and error-prone.
2.2 parameter Type Change
package com.ray.testobject;public class Test {private void info(int id) {}private void info(String id) {}public static void main(String[] args) {}}
We can better distinguish the two methods by changing the type.
Note: During the overload process, pay attention to the range of parameter types.
package com.ray.testobject;public class Test {private void info(char id) {System.out.println(char id: + id);}private void info(int id) {System.out.println(int id: + id);}public static void main(String[] args) {new Test().info(2);}}
Output:
Int id: 2
Generally, unless the char type is used specially, the overload of the char id function in Test will never be used, because most of the input parameters are automatically upgraded to int.
In addition, the compiler automatically selects a method to implement the budget. For example:
package com.ray.testobject;public class Test {private void info1(short id) {System.out.println(short id);}private void info1(int id) {System.out.println(int id);}private void info2(int id) {System.out.println(int id);}private void info2(short id) {System.out.println(short id);}public static void main(String[] args) {double x = 0;new Test().info1((int) x);new Test().info2((short) x);}}
Output:
Int id
Short id
As shown in the preceding output, the compiler automatically selects an appropriate type based on the parameter.