Java Examples - Method Overloading
First, let's look at the definition of method overloading: If two methods have the same method name but different parameters, then one method can be said to be an overload of the other method. The details are as follows:
- The method names are the same
- The parameter types and parameter counts of the methods are different
- The return types of the methods can be different
- The modifiers of the 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:
MainClass.java file
class MyClass {
int height;
MyClass() {
System.out.println("No-argument constructor");
height = 4;
}
MyClass(int i) {
System.out.println("The height of the house is" + i + "Rice");
height = i;
}
void info() {
System.out.println("The height of the house is" + height + "Rice");
}
void info(String s) {
System.out.println(s + ": The height of the house is" + height + "Rice");
}
}
public class MainClass {
public static void main(String[] args) {
MyClass t = new MyClass(3);
t.info();
t.info("Overloaded method");
//Overloaded constructor
new MyClass();
}
}
The output of the above code is:
房子高度为 3 米 房子高度为 3 米 重载方法: 房子高度为 3 米 无参数构造函数Other extensions
Java Examples