1、java中允许在同一各类中,多个同名方法的存在,但要求形参列表不一致。
重载:一样的方法名字,
System.out.println(100);
System.out.println("100");
System.out.println(100.1);
System.out.println('1');
System.out.println();

import java.util.Scanner;
public class Change{
public static void main(String[] args){
MyCalculator p1 = new MyCalculator();
int res = p1.calculate(1,2,5);
System.out.println("输出的结果是" + res);
}
}
class MyCalculator{
public int calculate(int i ,int j){
return i + j;
}
public double calculate(int i ,double j){
return i + j;
}
public int calculate(int i,int j ,int k){
return i + j + k;
}
}
一段代码就ok了。注意返回值 的接受定义的数据类型。

import java.util.Scanner;
public class Change{
public static void main(String[] args){
Methods p1 = new Methods();
int res0 = p1.max(1,1);
System.out.println("1输出的结果是" + res0);
double res1 = p1.max(1,1.2);
System.out.println("1输出的结果是" + res1);
double res2 = p1.max(1,5.1,5.5);
System.out.println("1输出的结果是" + res2);
}
}
class Methods{
public int max(int i ,int j){
if (i > j ) {
return i;
}else{
return j;
}
//return i >j ? i : j;
}
public double max(int i ,double j){
if (i > j ) {
return i;
}else{
return j;
}
}
public double max(double i, double j, double k){
double max = i > j ? i : j ;
if (max > k) {
return max;
}else{
return k;
}
}
}
变量一定要定义。
这篇博客探讨了Java中的方法重载概念,通过System.out.println()的多个重载实例进行说明。此外,展示了两个类`MyCalculator`和`Methods`中不同参数列表的方法重载实现,用于执行加法和求最大值操作。示例代码详细解释了如何根据参数类型和数量定义不同的方法。
623

被折叠的 条评论
为什么被折叠?



