public class Player implements Comparable<Player> {
//Fields
private Name name;
private Rollable rollable;
//Constructors
public Player() {
name = new Name();
rollable = new Rollable();
}
public Player(Name name) {
this.name = name;
rollable = new Rollable();
}
public Player(Name name, Rollable rollable) {
this.name = name;
this.rollable = rollable;
}
你好,对于我放置rollable = new Rollable();
的构造函数,我收到一条错误消息,指出它是Cannot instantiate the type rollable
。
在下面,我添加了JUnit测试,还将添加Rollable类的代码
@Test
public void testDefaultConstructor() {
Player p = new Player();
assertEquals("Name field should be initialised with a default Name object ", new Name(), p.
getName()); assertTrue(“播放器的rollable字段应使用Rollable接口的实现实例初始化”,p.getRollable()Rollable实例); }
@Test
public void testCustomConstructor1arg() {
Name n = new Name("Joe", "Bloggs");
Player p = new Player(n);
assertSame("Player's name field should be initialised with and return the same object received by the constructor", n, p.getName());
assertTrue("Player's rollable field should be initialised with an implementing instance of the Rollable interface", p.getRollable() instanceof Rollable);
}
下面是默认构造函数的JUnit测试,它也给我带来Players rollable field should be initialised with an implementing instance of the Rollable interface
的失败,但是,我所有其他的JUnit测试都通过了。
@Test
public void testDefaultConstructor() {
Player p = new Player();
assertEquals("Name field should be initialised with a default Name object ", new Name(), p.getName());
assertTrue("Player's rollable field should be initialised with an implementing instance of the Rollable interface", p.getRollable() instanceof Rollable);
}
我的Rollable类的代码如下;
public interface Rollable {
public void roll();
public int getScore();
}
我的可滚动代码的方法如下;
//Methods
public Name getName() {
return name;
}
public void setName(Name name) {
this.name = name;
}
public Rollable getRollable() {
return rollable;
}
public void rollDice() {
rollable.roll();
}
public int getDiceScore() {
return rollable.getScore();
}
感谢所有帮助,因为我正为失败而苦苦挣扎。
答案 0 :(得分:0)
您的getRollable()
方法是:
public Rollable getRollable() {
return rollable;
}
因此,如果您从构造函数中调用它,例如:
public Player() {
name = new Name();
rollable = getRollable();
}
然后为rollable
分配值rollable
,默认情况下为null
。
这样,当您在测试中再次调用getRollable()
时,您将获得分配给该字段的值-null
-并且根据定义-null instanceof Rollable
为假。
相反,您需要创建Rollable
的新实例,例如:
rollable = new Rollable();
(不知道它是否可以直接实例化。您尚未提供Rollable
类的声明。)
答案 1 :(得分:0)
您的Rollable
是一个接口,在Java中,您只能创建非抽象类的实例。
因此,您需要至少编写一个implements Rollable
的类。在此类中,您可以创建实例。
为什么会这样?
例如, Comparable
界面(作为我的Rollable
的类比)。 Comparable
表示通过要求类具有名为compareTo()
的方法来支持某种大于/等于/小于比较的类。如果要实例化Comparable
,您期望得到什么结果? String
,Long
,Double
还是什么?同样适用于您的Rollable
。
接口定义了实现类必须满足的一些要求,但它们并不表示类本身,因此您不能创建(直接)接口实例。