链表和继承问题

时间:2018-09-17 02:09:58

标签: java object inheritance linked-list

从子类中创建一个对象,并分配给名为theenemy的变量

从子类中创建第二个对象,并分配给名为enlink2的变量

调用第一个对象的继承的“ set”方法,并将其引用传递给第二个对象

调用第二个对象的继承的“ set”方法,并将其引用传递给第一个对象

public class ALink {

private ALink next;

public void setNext(ALink x) {

next = x;

  }

public ALink getNext (  ) {

return next;

    }

 }

public class Zombie extends ALink  {

private int attackmode;

public void set_attackmode(int  am) {

attackmode = am;

 }

public int get_attackmode (  ) {

return attackmode;

   }

}

这是我的输入内容

Zombie theenemy = new Zombie();

Zombie enlink2 = new Zombie();

theenemy.setNext(enlink2);

enlink2.setNext(theenemy);

遇到意外的标识符错误,不确定我哪里出错了吗?

2 个答案:

答案 0 :(得分:1)

父类的私有变量不属于子类。更改ALink中next的访问说明,将其设置为protected,然后它应该起作用。

答案 1 :(得分:0)

我不确定您要在这里实现什么,但是您的代码段对我来说没有任何问题。您在哪一行出错?

我用一条额外的Sysout语句尝试了您的代码,并获得了正确的输出:

    public class ALink {
    private ALink next;

    public void setNext(ALink x) {
        next = x;
        System.out.println("setNext is  called for " + x.getClass().getName());
    }

    public ALink getNext() {

        return next;

    }
}

public class Zombie extends ALink {

    private int attackmode;

    public void set_attackmode(int am) {
        attackmode = am;
    }

    public int get_attackmode() {
        return attackmode;
    }

}

public class TestZombie {
    public static void main(String[] args) {
        Zombie theenemy = new Zombie();

        Zombie enlink2 = new Zombie();

        theenemy.setNext(enlink2);

        enlink2.setNext(theenemy);
    }
}

获得以下输出:

setNext is  called for Zombie
setNext is  called for Zombie