方法的重载(Overload)+ println重载
2024-10-21 09:33:00
方法的重载(Overload)
package cn.day01;
/*方法的重载(Overload):多个方法的名称一样,但是参数列表不一样。
* 好处:只需要记住唯一一个方法名称,就可以实现类似多个功能
*
* 方法重载与下列因素有关:
* 1.参数个数不同
* 2.参数类型不同
* 3。参数的多类型顺序不同
*
* 方法重载与下列因素无关:
* 1.与参数的名称无关
* 2.与方法的返回值类型无关
*
* Tips:
* byte short int long float double char boolean
* String
* 在调用输出语句的时候,println方法其实是进行了多种数据类型的重载形式。
* */
public class MethodOverload {
public static void main(String[] args) {
System.out.println(sum(10, 20));
System.out.println(sum(10, 20, 30));
System.out.println(sum(10, 20, 30, 40));
//System.out.println(sum(10,20,30,40,50));
}
public static int sum(int a, int b) {
System.out.println("两个参数");
return a + b;
}
//错误写法!与方法的返回值类型无关
/* public static double sum(int a, int b) {
System.out.println("两个参数");
return a + b + 0.0;
}*/
//错误写法!!与参数名称无关
/* public static int sum(int x, int y) {
return x + y;
}*/
public static int sum(double a, double b) {
// System.out.println("两个参数");
return (int) (a + b);
}
public static int sum(int a, double b) {
return (int) (a + b);
}
public static int sum(double a, int b) {
return (int) (a + b);
}
public static int sum(int a, int b, int c) {
System.out.println("3个参数");
return a + b + c;
}
public static int sum(int a, int b, int c, int d) {
System.out.println("4个参数");
return a + b + c + d;
}
}
println重载
例题
package cn.day01;
/*
* 题目要求:
* 比较两个数据是否相等。
* 参数类型分别是两个byte类型,两个short类型,两个int类型,两个long类型,
* 并在main方法中进行测试。
* */
public class OverloadSame {
public static void main(String[] args) {
byte a = 10;
byte b= 20;
System.out.println(isSame(a,b));
System.out.println(isSame((short) 10,(short) 20));
System.out.println(isSame(11,12));
System.out.println(isSame(10L,10L));
}
public static boolean isSame(byte a, byte b) {
System.out.println("两个byte参数的方法执行!");
boolean same;
if (a == b) {
same = true;
} else {
same = false;
}
return same;
}
public static boolean isSame(short a, short b) {
System.out.println("两个short参数的方法执行!");
boolean same = a == b ? true : false;
return same;
}
public static boolean isSame(int a, int b) {
System.out.println("两个int参数的方法执行!");
return a == b;
}
public static boolean isSame(long a, long b) {
System.out.println("两个long参数的方法执行!");
if (a == b) {
return true;
} else {
return false;
}
}
}
执行结果
两个byte参数的方法执行!
false
两个short参数的方法执行!
false
两个int参数的方法执行!
false
两个long参数的方法执行!
true
最新文章
- JS二维数组排序组合
- JVM之GI收集器
- Redis 集群方案
- ListView优化-ViewHolder的优化备份
- JVM常见的七种垃圾收集器的简单比较
- JQuery EasyUI弹出对话框解决Asp.net服务器控件无法执行后台代码的方法(转)
- 函数flst_get_last
- Solr自动生成ID
- 前端框架Vue入门
- Codeforces 1144F Graph Without Long Directed Paths (DFS染色+构造)
- xxx.jar或者xxx.war中没有主清单属性和spring-boot-maven-plugin的作用
- solr安装配置(一)
- SQLite 数据库介绍和基本用法
- 数据库与java的连接
- 2017-2018-2 20165315 实验三《敏捷开发与XP实践》实验报告
- mysql密码篇(一)
- mysql中文显示问号,不能识别中文的解决方案
- excel怎么在插入的方框上打勾
- 138. Copy List with Random Pointer (Graph, Map; DFS)
- java调试器