Home  >  Article  >  Java  >  java method overloading example

java method overloading example

高洛峰
高洛峰Original
2017-01-19 14:44:531931browse

What is method overloading?

Method overloading is a means of handling different data types in a unified way.

How to constitute method overloading?

The method names are the same but the formal parameters are different. The difference in formal parameters is expressed in: 1). The number of formal parameters is different 2). The types of formal parameters are different 3). The order of formal parameters is different

Notes

1. If the return values ​​of the two methods are different, but everything else is the same. This does not constitute method overloading. An error will be reported during compilation:

Sample code (wrong): Test.java

/*返回值的不同并不能构成方法的重载*/
public class Test {
    public static void main(String[] args) {

    }   
}
class A { 
    public void f() {               //返回值为 void
    }  
    public int f() {                //返回值为 int, 其他和上面的f()方法是一样的
        return 1;
    }   
}

Error message:

Test.java:12: error: method f() is already defined in class A
      public int f() {
               ^
          1 error

2. 构造方法和普通方法一样, 也可以方法重载。

Sample code (correct): Test.java

/* 方法的重载
 * 输出结果:
 * public A() {} 这个构造方法被调用了
 * public A(int i) {} 这个构造方法被调用了
 * public void f() {} 这个构造方法被调用了
 * public void f(int i) {} 这个构造方法被调用了
 */
public class Test {
    public static void main(String[] args) {
        A aa1 = new A();                //调用9行那个方法
        A aa2 = new A(1);               //调用13行那个方法
        aa1.f();                        //调用17行那个方法
        aa2.f(1);                       //调用21行那个方法
    }   
}

class A { 
    public A() {                    //9行
        System.out.printf("public A() {} 这个构造方法被调用了\n");
    }  
    public A(int i) {               //13行
        System.out.printf("public A(int i) {} 这个构造方法被调用了\n");
    }  
    public void f() {               //17行
        System.out.printf("public void f() {} 这个构造方法被调用了\n");
    }  
    public void f(int i) {          //21行
        System.out.printf("public void f(int i) {} 这个构造方法被调用了\n");
    }   
}

For more articles related to java method overloading examples, please pay attention to the PHP Chinese website!

Statement:
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