时间:2023-03-09 12:09:36 | 栏目:JAVA代码 | 点击:次
修饰符 返回值类型 方法名( 形参列表 )
{
//方法体
return 返回值;
}
范例:

方法必须通过程序调用 才能运行,调用格式如下:
方法名(…);
范例:
int sum = add(10, 20); System.out.println(sum);
设计一个方法(无参、无返回值)用于打印两个数字的大小关系
编码实现:
public static void main(String[] args)
{
getRelation();//调用方法
}
public static void getRelation()
{
int a=10;
int b=20;
if(a>b)
{
System.out.println("a大于b");
}
else if(a<b)
{
System.out.println("a小于b");
}
else
{
System.out.println("a等于b");
}
}
输出结果:
a小于b
设计一个方法(有参、无返回值)用于打印两个数字的最大值
编码实现:
public static void main(String[] args)
{
getMax(10,20);//调用方法
}
public static void getMax(int a,int b)//带参无返回值
{
if(a>b)
{
System.out.println(a);
}
else
{
System.out.println(b);
}
}
输出结果:
20
设计一个方法(有参、有返回值 int 型)用于打印两个数字的最大值
编码实现:
public static void main(String[] args)
{
System.out.println(getMax(10,20));//调用方法
}
public static int getMax(int a,int b)//带参无返回值
{
if(a>b)
{
return a;
}
else
{
return b;
}
}
输出结果:
20

定义:同一个类中,出现多个方法名称相同,但是形参列表不同(类型不同或数量不同),与返回值无关
例如下面几个例子,判断是否为方法重载?

构造三个重载的方法,分别实现两个int型整数相加的和、两个double类型数据相加的和、三个int类型数据相加的和
编码实现:
public static void main(String[] args)
{
int result=sum(10,20);
System.out.println(result);
double result1=sum(10.0, 20.0);
System.out.println(result1);
int result2=sum(10, 20,30);
System.out.println(result2);
}
public static int sum(int a,int b)
{
return a+b;
}
public static double sum (double a,double b)
{
return a+b;
}
public static int sum(int a,int b,int c)
{
return a+b+c;
}
输出结果:
30
30.0
60