栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Java入门第五天3-java的方法重载

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Java入门第五天3-java的方法重载

1、方法重载的概述和特点
  • 方法重载概述
    • 在同一个类中,允许存在一个以上的同名方法,只要它们的参数个数或者参数类型不同即可。
  • 方法重载特点
    • 与返回值类型无关,只看方法名和参数列表
    • 在调用时,虚拟机通过参数列表的不同来区分同名方法
public class MethodDemo {
	public static void main(String[] args) {
		//定义两个变量
		int a = 10;
		int b = 20;
		
		//求和
		int result = sum(a,b);
		System.out.println("result:"+result);
		
		//定义变量
		int c = 30;
		//int result2 = sum2(a,b,c);
		int result2 = sum(a,b,c);
		System.out.println("result2:"+result2);
	}
	
	
	
	public static float sum(float a,float b) {
		return a + b;
	}
	
	//求三个数据的和
	
	public static int sum(int a,int b,int c) {
		return a + b + c;
	}
	
	//求两个数据的和
	public static int sum(int a,int b) {
		
		
		return a + b;
	}
}
2、方法重载练习之比较两个数据是否相等

需求:比较两个数据是否相等。
参数类型分别为两个byte类型,两个short类型,两个int类型,两个long类型,
并在main方法中进行测试

public class MethodTest {
	public static void main(String[] args) {
		//System.out.println(compare(10, 20));
		
		//System.out.println(compare((byte)10, (byte)20));
		
		//System.out.println(compare((short)10, (short)20));
		
		System.out.println(compare(10L, 20L));
	}
	
	
	public static boolean compare(byte a,byte b){
		
		System.out.println("byte");
		return a == b;
	}
	
	//两个short类型
	public static boolean compare(short a,short b){
		System.out.println("short");
		return a == b;
	}
	
	//两个int类型
	public static boolean compare(int a,int b){
		System.out.println("int");
		return a == b;
	}
	
	//两个long类型
	public static boolean compare(long a,long b){
		System.out.println("long");
		return a == b;
	}
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1006473.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号