Java method overloading example

  • 2020-04-01 03:11:27
  • OfStack

What is method overloading?

Method overloading is a means of dealing with different data types in a uniform way.

How to construct method overloads?

The method name is the same, but the parameter is different. The difference of formal parameter is expressed in:   1). Different number of formal parameters   3). The order of parameters is different

Matters needing attention

1. If the return value of two methods is different and the rest is the same. This time does not constitute an overload of the method. Errors are reported at compile time:

Sample code (error) : test.java



public class Test {
    public static void main(String[] args) {

    }   
}
class A { 
    public void f() {               //The return value is void
    }   
    public int f() {                //The return value is int, which is the same as the f() method above
        return 1;
    }   
}

Error message:


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

2.  The construction method is the same as the normal method,   Method overloading is also possible. 


Sample code (correct) : test.java



public class Test {
    public static void main(String[] args) {
        A aa1 = new A();                //Call the line 9 method
        A aa2 = new A(1);               //Call the line 13 method
        aa1.f();                        //Call the method on line 17
        aa2.f(1);                       //Call the line 21 method
    }   
}
class A { 
    public A() {                    //Line 9
        System.out.printf("public A() {}  The constructor is called n");
    }   
    public A(int i) {               //Line 13
        System.out.printf("public A(int i) {}  The constructor is called n");
    }   
    public void f() {               //17 rows
        System.out.printf("public void f() {}  The constructor is called n");
    }   
    public void f(int i) {          //Line 21
        System.out.printf("public void f(int i) {}  The constructor is called n");
    }   
}


Related articles: