JAVA -- 类与对象(三)方法重载
方法重载
添加实例化的变量名在 方法 的参数里,例如:hero h1
例如想调用name,就是h1.name。
在主程序入口内仍需要实例化,并给赋值。
本例子中的name 不需要使用 实例化.name 方法调用,但需要在主程序中实例化。
最后调用重载的方法 也是用 此文件中的实例化的类名进行调用的。
public class adhero extends hero{
int damage = 100;
public void attack(hero h1){
System.out.println(name + "对" + h1.name + "进行了一次攻击");
System.out.println("血量还有" + --h1.hp);
}
public void attack(hero h1,hero h2){
System.out.println(name + "对" + h1.name + "还有" + h2.name + "攻击一次");
}
public static void main(String args[]){
adhero a = new adhero();
a.name = "德玛西亚";
hero h1 = new hero();
h1.name = "德莱厄斯";
h1.hp = 100;
hero h2 = new hero();
h2.name = "寒冰射手";
a.attack(h1);
}
}
可变数量的参数
public void method(hero... heros)
下面是完整代码:
public class adhero extends hero {
int damage = 100;
public void attack(hero h1) {
System.out.println(name + "对" + h1.name + "进行了一次攻击");
System.out.println("血量还有" + --h1.hp);
}
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 ad = new adhero();
ad.name = "德玛";
hero h1 = new hero();
h1.name = "锐雯";
hero h2 = new hero();
h2.name = "刀妹";
ad.attack(h1,h2);
}
}
综合练习:治疗
public class support extends hero {
int damage = 100;
public void heal(hero h1, int hp) {
System.out.println(name + "对" + h1.name + "进行了一次治疗");
System.out.println("血量还有" + ++hp);
}
public static void main(String args[]){
support s = new support();
s.name = "琴女";
hero h1 = new support();
h1.name = "盖伦";
s.heal(h1,100);
}
}
