//单位原型
public class Prototype {
String name;//名字
int hp;//生命值
int atk;//攻击力
int def;//防御力
//通过使用构造方法初始化属性
public Prototype(String name,int hp,int atk,int def){
this.name=name;
this.hp=hp;
this.atk=atk;
this.def=def;
}
//展示单位的各项属性
public void dis(){
System.out.println("");
System.out.println("英雄血量:"+hp);
System.out.println("英雄攻击:"+atk);
System.out.println("英雄防御:"+def);
}
}
//继承自单位原型类的英雄类
public class Hero extends Prototype{
public Hero(String name, int hp, int atk, int def) {
super(name, hp, atk, def);
}
}
//继承自单位原型类的怪物类
public class Monster extends Prototype{
public Monster(String name, int hp, int atk, int def) {
super(name, hp, atk, def);
}
}
public class Play {
public static void main(String[] args) {
Prototype hero1=new Hero("李逍遥",600,70,30);
Prototype hero2=new Hero("克劳德",700,60,35);
Prototype monster1=new Monster("杂兵",400,50,25);
Prototype monster2=new Monster("Boss",500,100,20);
pk(hero1,monster1);
pk(hero1,hero2);
pk(monster1,monster2);
pk(monster2,hero2);
}
public static void pk(Prototype p1,Prototype p2){
System.out.println(p1.name+"的各项属性为");
p1.dis();
System.out.println("");
System.out.println("");
System.out.println(p2.name+"的各项属性为");
p2.dis();
if(p1.hp/(p2.atk-p1.def)>p2.hp/(p1.atk-p2.def))
{
System.out.println(p1.name+" vs "+p2.name+" is victory");
}
else
System.out.println(p1.name+" vs "+p2.name+" is defeat");
}
}
运行结果如下:
总结:
继承很好的模拟了现实生活中对象之间的关系,而在程序设计中,继承又能很好的帮助程序员减少很多重复代码。除此之外,由于自动转型功能的存在,使得在定义方法时,不必定义多个不同的方法来放入不同的子类参数,而只需要一个父类参数即可,大大方便了程序设计人员。而方法重写的存在又使得子类更为多样化,而不是完全照搬自父类。
继承的方便性体现在重用性,灵活性体现在拓展性,是java程序设计中常用又方便的一环。