您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

详细讲解JAVA中方法重载概念——简单易懂

2026/1/10 17:04:11发布14次查看
1、什么方法重载?
方法的重载指的是方法名一样,但是参数类型不一样
1.1、attack方法重载
有一种英雄,叫做物理攻击英雄 adhero,为adhero 提供三种方法。
public void attack()public void attack(hero h1)public void attack(hero h1, hero h2)
方法名是一样的,但是参数类型不一样
在调用方法attack的时候,会根据传递的参数类型以及数量,自动调用对应的方法
public class adhero extends hero { public void attack() { system.out.println(name + " 进行了一次攻击 ,但是不确定打中谁了"); } public void attack(hero h1) { system.out.println(name + "对" + h1.name + "进行了一次攻击 "); } public void attack(hero h1, hero h2) { system.out.println(name + "同时对" + h1.name + "和" + h2.name + "进行了攻击 "); } public static void main(string[] args) { adhero bh = new adhero(); bh.name = "赏金猎人"; hero h1 = new hero(); h1.name = "盖伦"; hero h2 = new hero(); h2.name = "提莫"; bh.attack(h1); bh.attack(h1, h2); } }
1.2、可变数量的参数
如果要攻击更多的英雄,就需要设计更多的方法,这样类会显得很累赘,像这样:
public void attack(hero h1)public void attack(hero h1,hero h2)public void attack(hero h1,hero h2,hero 3)
这时,可以采用可变数量的参数
只需要设计一个方法
public void attack(hero ...heros)
即可代表上述所有的方法了
在方法里,使用操作数组的方式处理参数heros即可
public class adhero extends hero { public void attack() { system.out.println(name + " 进行了一次攻击 ,但是不确定打中谁了"); } // 可变数量的参数 public void attack(hero... heros) { for (int i = 0; i < heros.length; i++) { system.out.println(name + " 攻击了 " + heros[i].name); } } public static void main(string[] args) { adhero bh = new adhero(); bh.name = "赏金猎人"; hero h1 = new hero(); h1.name = "盖伦"; hero h2 = new hero(); h2.name = "提莫"; bh.attack(h1); bh.attack(h1, h2); } }
练习: 治疗
(设计一个类support (辅助英雄)继承hero,提供一个heal(治疗)方法
对support的heal方法进行重载
heal()
heal(hero h) //为指定的英雄加血
heal(hero h, int hp) //为指定的英雄加了hp的血)
答案
public class support extends hero { public void heal() { system.out.println("对自己进行治疗"); } public void heal(hero hero) { system.out.println("给英雄 " + hero + " 加血"); } public void heal(hero hero, int hp) { system.out.println("给英雄 " + hero + " 加了 " + hp + "点血"); } }
更多相关内容请访问:java视频教程
以上就是详细讲解java中方法重载概念——简单易懂的详细内容。
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product