Java custom functions and function overloading

custom function

insert image description here

Key Points:

  1. Functions must be placed in a class
  2. Modifiers public, static, return value, int, void, char... function name (formal parameter list) {function body}
  3. Usually, methods are public modified, public, easy to call
  4. Functions can call functions, classes such as main function call...
  5. For recursive functions, pay attention to the termination condition

Custom function instance for recursive factorial

public class Demo07 {
    
    
    public static void main(String[] args) {
    
    
        int a = 5;
        System.out.println(a(a));
    }
    //自定义函数,函数调用自己,只不过对参数进行了-1操作
    public static int a(int a){
    
    
        if(a>1){
    
    
            return a*a(a-1);
        }else{
    
    
            return 1;
        }
    }
}

insert image description here

function overloading

In a class, the function name is the same, that is, overloading. It should be noted that the parameters of the overloaded function 个数or 类型must be different.

The function name is the same, the parameters are the same, the return value is different, and this is wrong, it is forbidden

public class Demo02 {
    
    
    public static void main(String[] args) {
    
    
        System.out.println(max(2.6,4.8,3.6));
    }
    public static int max(int a,int b){
    
    
        int c = a>b?a:b;
        return c;
    }
    public static double max(double a,double b){
    
    
        double c = a>b?a:b;
        return c;
    }
    public static double max(double a,double b,double c){
    
    
        if(a>b){
    
    
            return a;
        }else if(b>c){
    
    
            return b;
        }else{
    
    
            return c;
        }
    }
}

insert image description here


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324305369&siteId=291194637