Talk about overloading the Java method

  • 2020-05-09 18:36:00
  • OfStack

Method overloading means that multiple methods with the same name but different parameters can be defined in one class. When called, the corresponding method will be selected according to the different parameter table

Such as


public class Test {
  void max(int a,int b) {
    System.out.println(a>b ? a:b);
  }
   
  void max(double a,double b) {
    System.out.println(a>b ? a:b);
  }
   
  public static void main(String[] args) {
    Test t = new Test();
    t.max(3,4);
    t.max(3.0,4.4);
  }
 
}

The output is:


 4
 4.4

Constructors can also be overloaded

Let's do another example


class ChongZai{
  public void a(int a);
   public void a(Strting a);
   public void a(int a,int b);
}

As shown above, an overload must satisfy the following conditions:
1. Must be the same class
2. Method name (or function) 1
3. No one parameter type or number

I'm also going to talk to LZ about the use of 1 overloading and   as an example above


ChongZai  cz =new ChongZai();
cz.a(1);          // call a(int a);
cz.a(" The parameters of the transmission ");   // call a(String a)
cz.a(1,2);         // call a(int a,int b)

We already said which method   is called and this method is called by the program based on the parameters you enter

So let's talk about reloading     just like if you're playing a game   then maybe you can play a game where you can have multiple people finish   and you don't know how many people finish   so you can use reloading    

Let's say there's a maximum of three people on   and then you can define three parameters


public void a(String a);
public void a(String a,String b);
public void a(String a,String b,String c);

Two people and you're going to call the method   with two parameters and three people and you're going to call the method     with three parameters and how do you do that


Related articles: