Java Example - Method Overloading


Java 实例 Java Example

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:

  • Method names are the same
  • The parameter types of the method have at least one different number in order
  • 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 
无参数构造函数

Java 实例 Java Example