Home >Java >javaTutorial >Java Example - Method Overloading
Let’s first look at the definition of method overloading: If there are two methods with the same method name but inconsistent parameters, how can we say that one method is an overload of another method. The specific instructions are as follows:
The method names are the same
The parameter types of the methods have at least one difference in the order of numbers
The return types of methods can be different
The modifiers of methods can be different
The main method can also be overloaded
The following example demonstrates how to overload the info method of the MyClass class:
/* 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 output result of running the above code is:
房子高度为 3 米 房子高度为 3 米 重载方法: 房子高度为 3 米 无参数构造函数
The above is the Java example - The content of method overloading, please pay attention to the PHP Chinese website (www.php.cn) for more related content!