类: (抽象的)相似属性,相似功能的对象可化为一类
程序中类由属性和方法组成
对象:(具体的)在现实生活中,一个具体的事物或一个具体的物体
程序中即将类实例化
例题:回合制对战游戏场景:奥特曼和小怪兽进行PK,直到一方的血量为0时结束战斗,
输出谁胜利了!
1.分析:建立两个类:person1(属性:name、blood、fight 方法:PK)
person2(同上)
Main函数 :
实例化类 person1(person1 p1 = new person1())
person2(person2 p2 = new person2())
调用PK函数
2.代码
package cxx.test0409;
public class Manger {
public static void main(String [] args){
person1 per1 = new person1();//实例化对象
per1.name = "奥特曼";//属性赋值
per1.blood = 10;
per1.fight = 3;
person2 per2 = new person2();
per2.name = "小怪兽";
per2.blood = 10;
per2.fight = 4;
while(per1.blood>0&&per2.blood>0){
per1.pk(per2);
if(per2.blood<=0)
break;
per2.pk(per1);
}
}
}
package cxx.test0409;
public class person1 {
public String name;
public int blood;
public int fight;
public void pk(person2 p2){
p2.blood -= fight;
System.out.println(name+"攻击了"+p2.name+","+p2.name+"剩余的血量是"+p2.blood);
if(p2.blood<=0){
System.out.println(name+"胜利!");
}
}
}<pre class="java" name="code">package cxx.test0409;
public class person2 {
public String name;
public int blood;
public int fight;
public void pk(person1 p1){
p1.blood -= fight;
System.out.println(name+"攻击了"+p1.name+","+p1.name+"剩余的血量是"+p1.blood);
if(p1.blood<=0){
System.out.println(name+"胜利!");
}
}
}