欢迎光临
我们一直在努力

以双方互攻为例,熟悉Java面向对象编程思想

本篇以模拟两英雄互相攻击,血量首次为空判输为例,揭示Java语言以面向对象编程的思想。
情景案例:设置后羿、公孙离两位英雄,以下为英雄属性:
后 羿 : 初始血量:单次伤害:
公孙离:初始血量:单次伤害:
两英雄循环攻击,直至出现一方血量为空结束。

各类属性方法如下:

在这里插入图片描述

思路如下:

掉血值类作为单独一个类,使用private关键字修饰掉血量,保证掉血量的安全性问题。即外部类只能通过getRestBlood()方法调用而不能修改。体现Java中三大特征中的封装思想。
在here类中定义名字、初始血量等成员变量。在确定掉血量时,创建了RestBlood的类对象并赋值。然后创建方法(攻击函数)。最后在main函数中创建两个hero对象,赋初始血量,调用攻击函数,使两英雄互相攻击,用if-else来根据双方剩余血量判断结果。

以下为重要代码展示:

RestBlood类:

package java01;
class RestBlood {
private int restBlood;
public RestBlood(int Blood) {
this.restBlood = Blood;
}
public int getRestBlood() { //提供get方法,供外部类得到掉血量
return restBlood;
}
}

攻击函数:

public void attack(Student target){
int damage=restBlood.getRestBlood();//掉血量从RestBlood中获取
target.setBlood(target.getBlood()-damage);//剩余血量=总血量-掉血量
System.out.println(name+"攻击"+target.getName()+","
+"掉血"+damage+",剩余"+target.getBlood());
}

循环攻击判定:

while(true){
houyi.attack(gongsunli);
if(gongsunli.getBlood()<=0){
System.out.println(houyi.getName()+"胜利");
break;
}
gongsunli.attack(houyi);
if(houyi.getBlood()<=0){
System.out.println(gongsunli.getName()+"胜利");
break;
}

hero类中构造方法:

public Student(String name, int initBlood) {
this.name = name;
this.blood = initBlood;
this.restBlood = new RestBlood(100);//设置每次攻击掉血量100
}

main函数中设置初始值:

Student houyi=new Student("后羿",1000);
Student gongsunli=new Student("公孙离",800);
System.out.println("后羿初始血量:"+houyi.getBlood());

结果演示:
在这里插入图片描述
通过案例,可以更深入了解不同类之间的联系与意义。通过提供适当的get、set方法来供外部使用,其体现出的封装性特点极大保护了类内部属性的安全性。

赞(0)
未经允许不得转载:171主机测评 » 以双方互攻为例,熟悉Java面向对象编程思想
分享到: 更多 (0)

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址