关于Java面向对象编程(对象的创建,类的继承)
类的创建
格式:public class 类名 { 属性,方法 }
类的继承
格式:public class 子类名 extends 父类名 { 属性,方法 }
子类可以继承父类的数据,保护 (protected) 公有 (public) 的方法,父类更加通用,而子类更加具体,类的继承可以大幅度的精简代码,提高其可维护性。
子类的方法会将父类的覆盖,如需使用父类的方法需要使用super 关键字
package legend;
//manage.java
public class manage {
public static void main(String[] agrs)
{
sublegends s1 = new sublegends();
s1.setAttack(100);
s1.setBlood(1287);
s1.setName("luban");
sublegends s2 = new sublegends();
s2.setAttack(80);
s2.setBlood(2841);
s2.setName("yase");
sublegends s3 = new sublegends();
s3.setAttack(120);
s3.setBlood(4000);
s3.setName("boss");
while(true)
{
if(s1.getBlood()>1000 &&s2.getBlood()>1000)
{
s1.attacks(s2);
s2.attacks(s1);
}
else
{
s1.attacks(s3);
s2.attacks(s3);
}
if(s1.state == 0 || s2.state == 0|| s3.state == 0)
{
System.out.println("game over");
break;
}
}
}
}
//legends.java
public class legends {
private int attack;
private int blood;
public void setAttack(int a)
{
attack = a;
}
public int getAttack()
{
return attack;
}
public void setBlood(int b)
{
blood = b;
}
public int getBlood()
{
return blood;
}
public void underAttack(int a)
{
blood -= a;
}
}
//sublegends.java
public class sublegends extends legends{
private String name;
public int state;
public void setName(String m)
{
name = m;
state = 1;
}
public String getName()
{
return name;
}
public void attacks(sublegends s1)
{
if(s1.state == 1)
{
System.out.println(getName()+" attacks " + s1.getName());
s1.underAttack(getAttack());
}
if(s1.getBlood()>0)
{
System.out.println(s1.getName() + "现在还剩" + s1.getBlood() + "点血量");
}
else
{
System.out.println(s1.getName()+ "已阵亡");
s1.state = 0;
}
}
}