一:主类中自定义函数
在主类中,如果想要在main函数中调用自定义的其他方法,则这个函数需要使用static关键字定义,否则会报错Cannot make a static reference to the non-static method xx from the type xx,调用的时候直接用函数名就可以了,如下:
public classcreate_function {public static voidmain(String []args){int s = jia(5,4);
System.out.println(s);}static int jia(int a, intb){
System.out.println("我是自定义相加函数,我被调用了!!");return a+b;
}
}
下面使用static关键字定义了一个“+”运算的函数,在main中调用时,直接使用函数名,括号中加参数就可以了。输出结果如下:
我是自定义相加函数,我被调用了!!9
二:自定义类中函数的调用
自定义类中函数的调用有两种情况,静态函数和非静态函数,非静态函数的调用需要先声明一个类实例,通过实例调用。静态函数的调用可以通过实例,也可以直接使用类名调用(建议使用这种,要不会造成内存空间的浪费。),如下:
public classcreate_function {public static voidmain(String []args){
Y y=newY();int s2 = y.cheng(3,5);
System.out.println(s2);int s3 = Y.chu(8, 2);
System.out.println(s3);
}}classY{int cheng(int a,intb){
System.out.println("我是自定义类中的乘方法,我被调用了!");return a*b;
}static int chu(int c,intd){
System.out.println("我是自定义类中的除方法,我被调用了!");return c/d;
}
}
在下面,自定义了一个Y类,cheng方法是非静态方法,必须通过实例y调用,chu方法是静态方法,使用类名直接调用。输出结果如下:
我是自定义类中的乘方法,我被调用了!15我是自定义类中的除方法,我被调用了!4
***************不积跬步无以至千里***************