Java Examples - Method overloading
First look at the method overloading (Overloading) definition: If there are two ways to approach the same name, but the parameters are inconsistent, it can be said that a method which is overloaded with another method. Specifically described as follows:
- The method of the same name
- Parameter type of the method, the order of at least a number of different
- Return type of the method may not be the same
- The method may not be the same modifier
- main method can also be overloaded
The following example shows how to reload MyClass class info methods:
/* author by w3cschool.cc MainClass.java */ class MyClass { int height; MyClass() { System.out.println("无参数构造函数"); height = 4; } MyClass(int i) { System.out.println("房子高度为 " + i + " 米"); height = i; } void info() { System.out.println("房子高度为 " + height + " 米"); } void info(String s) { System.out.println(s + ": 房子高度为 " + height + " 米"); } } public class MainClass { public static void main(String[] args) { MyClass t = new MyClass(3); t.info(); t.info("重载方法"); //重载构造函数 new MyClass(); } }
The above code is run output is:
房子高度为 3 米 房子高度为 3 米 重载方法: 房子高度为 3 米 无参数构造函数