Java方法调用和参数传递

一、Java中main函数调用同类下方法或变量

有时候我们想调用main方法那个类中的其他方法,这时有两种方式:

方式1,使用static修饰那个方法

public class
test {
    public static void main(String[] args) {
        int te=2;
        test(te);
    }
    static void test(int a){
        System.out.println(a);
    }
}

方式2,创建一个类的对象,利用这个对象来进行调用

public class
test {
    public static void main(String[] args) {
        int te=2;
        test t=new test();
        t.test_func(te);
    }
    void test_func(int a){
        System.out.println(a);
    }
}

第一种方法不用创建一个新对象的实例,因为在程序载入的时候已经分配了内存空间,而第二种方法通过创建了一个对象的实例分配到了内存空间。

二、java方法的参数传递

2.1 数组作为参数的传递

public class
test {
    public static void main(String[] args) {
        int[] a=new int[]{0,1};
        test_func(a);
        System.out.println(a[0]);
        System.out.println(a[1]);
    }
    public static void test_func(int[] arr){
        arr[0]=1;
        arr[1]=2;
    }
}

因为数组是引用变量,传递的参数是数组的地址,因此在调用方法内对数组进行改变会导致原来的数据改变。

猜你喜欢

转载自blog.csdn.net/kking_edc/article/details/107301169