Home > Java > javaTutorial > body text

Java Example - Method Overloading

黄舟
Release: 2017-02-16 10:04:39
Original
1715 people have browsed it

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();
   }}
Copy after login

The output result of running the above code is:

房子高度为 3 米
房子高度为 3 米
重载方法: 房子高度为 3 米
无参数构造函数
Copy after login

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!


source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!