想请教一个问题

[复制链接]
查看11 | 回复2 | 2006-8-10 17:13:00 | 显示全部楼层 |阅读模式
题目要求:
写1个接口, 名为Attackable(可以被攻击的), 它有一个方法为void attacked (attacker Attacker);这个方法在对象被攻击时调用
写1个接口, 名为Attacker(攻击者), 它有一个方法为void attack( Attackable enemy );这个方法可以攻击任何实现Attackable的对象
写1个类Unicorn(独角兽)实现Attackable接口, 当它被攻击时打印出”我被攻击了, 救命!”
写1个类Ghost(鬼)实现Attacker接口, 当它袭击其他Attackable对象时, 打印出”你被鬼附身了”
写1个测试类测试上述类, 在测试类的main方法中创建出Unicorn(独角兽)对象和Ghost(鬼)对象,并用Ghost(鬼)对象 攻击 Unicorn(独角兽) 对象
下面是我自己写的代码:
public interface Attackable{
abstract public void attacked(attacker Attacker);
}
interface attacker extends Attackable{
abstract public void attack(Attackable enemy);
}
class Unicorn implements Attackable{
boolean flag;
public void attacted (attacker Attacker){
{
System.out.println ("我被攻击了,救命啊!&quot

;
}
}
}
abstract class Ghost implements attacker{
boolean flag;
public void attacted (Attackable enemy){
if (flag==true){
System.out.println ("嘿嘿,你被鬼苻身了&quot

;
}
}

}
/*写1个测试类测试上述类, 在测试类的main方法中创建出Unicorn(独角兽)对象和Ghost(鬼)对象, 并用Ghost(鬼)对象 攻击 Unicorn(独角兽) 对象.*/
class test{
public static void main(String []args){
Attackable beast=new Unicorn();
attacker spook=new Ghost();
        //这里有问题,该怎么实现攻击呢?还是我前面的也错了
}

}
回复

使用道具 举报

千问 | 2006-8-10 17:13:00 | 显示全部楼层
呵呵,刚才看到你的题目很有趣,看了看,你可以这样:
public interface Attackable
{
void attacked(Attacker attacker);
}
public interface Attacker
{
void attack(Attackable attackable);
}
public class Unicorn implements Attackable
{
public void attacked(Attacker attacker)
{
System.out.println("我被攻击了,救命!&quot

;
}
}
public class Ghost implements Attacker
{
public void attack(Attackable attackable)
{
System.out.println("你被鬼附身了!&quot

;
}
}
测试类主方法写:
public static void main(String[] args)
{
Unicorn unicorn = new Unicorn();
Ghost ghost = new Ghost();
ghost.attack(unicorn);
unicorn.attacked(ghost);
}
你看看,如果有误请更正!
回复

使用道具 举报

千问 | 2006-8-10 17:13:00 | 显示全部楼层
我调试了一下,楼上第一个的public的类太多了如果在同一个java文件会有点问题,只能有一个public类.
public interface Attackable
{
void attacked(Attacker attacker);
}
interface Attacker
{
void attack(Attackable attackable);
}
class Unicorn implements Attackable
{
public void attacked(Attacker attacker)
{
System.out.println("我被攻击了,救命!&quot

;
}
}
class Ghost implements Attacker
{
public void attack(Attackable attackable)
{
System.out.println("你被鬼附身了!&quot

;
}

}
class Test{
public static void main(String[] args)
{
Unicorn unicorn = new Unicorn();
Ghost ghost = new Ghost();
ghost.attack(unicorn);
unicorn.attacked(ghost);
}
}
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

主题

0

回帖

4882万

积分

论坛元老

Rank: 8Rank: 8

积分
48824836
热门排行