方法五要素:
- public :访问修饰符
- static :静态修饰
- void :返回值占位符 当方法没有返回值的时候使用void占位
- main :方法名
- String[] args{}: 中 String[]参数的数据类型 args 参数名称相当与变量 {} 方法体
()里面为参数列表
return();为返回值,没有这个语句就是没有返回值
方法的定义有以下几种:
1 无参数无返回值类型
此类方法可以直接在主函数中输入方法名来调用
public static void fun01(){
System.out.println("鸡汤来喽");
}
public class Demo01 {
public static void main(String[] args) {
fun01();
}
输出结果
2 无参数有返回值类型
调用时需要用一个变量来接受返回值,然后在输出变量的值
public static int fun02(){
return 10086;
}
public static void main(String[] args) {
int fun02 = fun02();
System.out.println(fun02);
输出结果
3有参数无返回值类型
此方法中有一个string类型的形参food,所以在调用此方法时需要给food赋值
public static void fun03(String food){
System.out.println("吃"+food);
//food为形参
}
public static void main(String[] args) {
fun03("核桃");
//在调用方法时传递给方法的参数为实际有真实值的参数,这个值被成为实际参数 简称实参
//实参的数据类型必须和形参一致,或者是形参的子类型
//有一种特殊的实参 引用类型
//核桃为实参
}
输出结果
4有参数有返回值
此类方法需要用一个变量来接受返回值,并且需要给形参赋值
public static String fun04(String name){
return"我的代号"+name;
}
public static void main(String[] args) {
String fun04 = fun04("穿山甲");
}
输出结果
5两个参数无返回值
直接在主函数中调用,并且给形参赋值
public static void fun05(int count,String food){
System.out.println("吃"+count+"个"+food);
}
public class Demo01 {
public static void main(String[] args) {
fun05(5,"馒头");
输出结果
6两个参数有返回值
此类方法需要用一个变量来接受返回值,并且需要给形参赋值
public static int fun06(int a,int b){
return a+b;
}
public static void main(String[] args) {
int fun06 = fun06(5,6);
System.out.println(fun06);
输出结果