圈小猫Java代码 圈小猫在线玩( 二 )


public static void main(String[] args){
Cat cat1 = new Cat("Tom" , 10);
Cat cat2 = new Cat("Sun" , 15 , "苹果树");
Dog dog1 = new Dog("lufy" , 5);
Dog dog2 = new Dog("nan" , 20 , "泳池");
cat1.start();
cat2.start();
dog1.start();
dog2.start();
}
}
abstract class Creature extends Thread
{
protected int life; //生物的寿命
protected String name = "";
protected String objname = "";
public void call(){};
public void eat(){};
public void active(int state){};
}
class Cat extends Creature
{
public Cat(String name , int life)
{
this.name = name;
this.life = life;
System.out.println("小猫" + name + "诞生了 , 寿命" + life);
}
public Cat(String name , int life ,String objname)
{
this.name = name;
this.life = life;
this.objname = objname;
System.out.println("小猫" + name + "诞生了 , 寿命" + life + "喜欢" + objname );
}
public void climb()
{
System.out.println("小猫" + name + "在爬树" );
}
public void climb(String objname)
{
System.out.println("小猫" + name + "在爬" + objname + "树");
}
@Override
public void call() {
System.out.println("小猫" + name + "停下来在喵喵的叫" );
}
@Override
public void eat() {
System.out.println("小猫" + name + "饿了,它在吃东西" );
}
@Override
public void active(int state) {
switch(state)
{
case 1:
if(objname.length()0)
climb(objname);
else
climb();
break;
case 2:
call();
break;
case 3:
eat();
break;
}
}
@Override
public void run() {
//你可以尝试在这里做一个状态机,控制动物的行为
int i = 0 ;
int state = 0 ;
while(ilife)
{
double rnd = Math.random();
state = (int)(rnd * 4);//随机出状态
active(state);
i++;
}
System.out.println("小猫" + name + "它的生命结束了,享年" + life);
}
}
class Dog extends Creature
{
public Dog(String name , int life)
{
this.name = name;
this.life = life;
System.out.println("小狗" + name + "诞生了 , 寿命" + life );
}
public Dog(String name , int life , String objname)
{
this.name = name;
this.life = life;
this.objname = objname;
System.out.println("小狗" + name + "诞生了 , 寿命" + life + "喜欢" + objname );
}
public void swim()
{
System.out.println("小狗" + name + "在游泳" );
}
public void swim(String objname)
{
System.out.println("小狗" + name + "在" + objname + "游泳");
}
@Override
public void call() {
System.out.println("小狗" + name + "停下来在喵喵的叫" );
}
@Override
public void eat() {
System.out.println("小狗" + name + "饿了,它在吃东西" );
}
@Override
public void active(int state) {
switch(state)
{
case 1:
if(objname.length()0)
swim(objname);
else
swim();
break;
case 2:
call();
break;
case 3:
eat();
break;
}
}
@Override
public void run() {
//你可以尝试在这里做一个状态机,控制动物的行为
int i = 0 ;
int state = 0 ;
while(ilife)
{
double rnd = Math.random();
state = (int)(rnd * 4);//随机出状态
active(state);
i++;
}
System.out.println("小狗" + name + "它的生命结束了 , 享年" + life);
}
}
java1.编写一个 Animal类,包括的属性年龄,名称;包括的方法: 构造方法和打印动物属性的方法代码如下圈小猫Java代码:

推荐阅读