java自定义函数调用

一:主类中自定义函数

在主类中,如果想要在main函数中调用自定义的其他方法,则这个函数需要使用static关键字定义,否则会报错Cannot make a static reference to the non-static method xx from the type xx,调用的时候直接用函数名就可以了,如下:

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

     int s = jia(5,4); System.out.println(s); } static int jia(int a, int b){ System.out.println("我是自定义相加函数,我被调用了!!"); return a+b; } }

下面使用static关键字定义了一个“+”运算的函数,在main中调用时,直接使用函数名,括号中加参数就可以了。输出结果如下:

我是自定义相加函数,我被调用了!!
9

二:自定义类中函数的调用

自定义类中函数的调用有两种情况,静态函数和非静态函数,非静态函数的调用需要先声明一个类实例,通过实例调用。静态函数的调用可以通过实例,也可以直接使用类名调用(建议使用这种,要不会造成内存空间的浪费。),如下:

public class create_function {
    
    public static void main(String []args){
        Y y =new Y();
        
        int s2 = y.cheng(3,5);
        System.out.println(s2);
        
        int s3 = Y.chu(8, 2);
        System.out.println(s3);
    } 
}

class Y{
    int cheng(int a,int b){
        System.out.println("我是自定义类中的乘方法,我被调用了!");
        return a*b;
    }
    static int chu(int c,int d){
        System.out.println("我是自定义类中的除方法,我被调用了!");
        return c/d;
    }
}

在下面,自定义了一个Y类,cheng方法是非静态方法,必须通过实例y调用,chu方法是静态方法,使用类名直接调用。输出结果如下:

我是自定义类中的乘方法,我被调用了!
15
我是自定义类中的除方法,我被调用了!
4

***************不积跬步无以至千里***************

原文地址:https://www.cnblogs.com/liangshian/p/11777570.html