Java方法基础学习

49 阅读1分钟

方法

方法是语句的集合,他们一起执行一个功能,方法命名是首字母小写后面的首字母大写

System.out.println();
//System是java.lang下面的一个类
// out是对象
// println是out对象下面的方法

System.out.println();

静态方法和非静态方法

静态方法可以直接调用在类里面, 但是不是静态方法需要new 对象然后通过对象调用

package 方法;

public class test_1 {
    public static void main(String[] args) {
        int a = add(10, 20);
        System.out.println(a);
        // 调用非静态方法
        new test_1().zwl();
    }
    // static 静态
    public static int add(int a, int b){
        return  a+b;
    }
    public void zwl(){
        System.out.println("非静态方法调用");
    }
}

方法的定义

java的方法类似其他的函数,主要通过一段语句来完成某件事

方法包含一个方法头和一个方法体

image.png

方法的重载

重载是方法名相同,但是传递的参数类型不同或者参数个数不同;

image.png

package 方法;

public class test_2 {
    public static void main(String[] args) {
        int a = add(10,20);
        double b = add(10.1, 20);
        int c = add(10,20,30);
    }
    // 方法的重载
    public static int add(int a, int b){
        return a+b;
    }
    public static double add(double a, int b){
        return a+b;
    }
    public static int add(int a, int b, int c){
        return a+b+c;
    }
}

方法的可变参数

image.png

递归

image.png

package 方法;

public class test_3 {
    public static void main(String[] args) {
        System.out.println( f(5));
    }
    //阶乘函数, 返回结果之后跳出循环就可以运行了
    public static int f(int n){
        if(n == 1){
            return 1;
        }else{
            return n*f(n-1);
        }
    }
}