我有两个类(class),Club
和party
。 Club
extends
通用Queue<E>
并实现 fitnessInterface
。
Queue<E> implements QueueInterface<E>
俱乐部
public class Club extends Queue<Bachelor> implements fitnessInterface{
protected Queue<Bachelor> bachelorQ;
public Club(){
super();
bachelorQ = new Queue<Bachelor>();
}
public boolean Eligible(Bachelor bachelor){
if(bachelor==null){throw new NullPointerException();}
return true;
}
@Override
public QueueInterface<Bachelor> enqueue(Bachelor bachelor){
if(bachelor==null){
throw new NullPointerException();
else{
bachelorQ.enqueue(bachelor); }
return this; //the class queue
}
}
聚会
public class Party extends Club{
super();
}
@Override
public boolean Eligible(Bachelor bachelor){
if(bachelor==null){throw new NullPointerException();}
if(bachelor.getPushups()>=25){return true;}
return false;
}
}
Bachelor
类扩展了 QueueInterface
并有一个接受 Integer
的构造函数作为参数,除其他外,还有 getPushUps()
方法。
问题是当我创建 Party
时反对并尝试将单例汉拉尔夫或查理排入队列,它仍然是空的。
我的通用队列类工作完美。它有dequeue
, enqueue
, isEmpty
, peek
, size
和toString
方法。一切工作正常。
主要
public static void main(String[] args){
Party bigParty = new Party();
Bachelor jack,charlie,ralph;
jack = new Bachelor(15);
ralph = new Bachelor(27);
charlie = new Bachelor(39);
//Eligibility tests
System.out.println(bigParty.Eligible(charlie));
System.out.println(bigParty.Eligible(ralph));
System.out.println(bigParty.Eligible(jack));
System.out.println(bigParty.enqueue(ralph));
System.out.println(bigParty.enqueue(charlie));
System.out.println(bigParty.size());
System.out.println(bigParty.bachelorQ.size());
}
输出
true
true
false
[]
[]
0
2
<小时/>
最佳答案
这就是当您混合继承和组合时会发生的情况。检查这个方法:
@Override
public QueueInterface<Bachelor> enqueue(Bachelor bachelor){
if(bachelor==null){
throw new NullPointerException();
bachelorQ.enqueue(bachelor);
return this; //the class queue
}
}
您正在调用enqueue()
上bachelorQ
,但返回this
。两者都是不同的引用,指向不同的对象。
您应该返回bachelorQ
,或者只是调用 super.enqueue(bachelor)
.
顺便说一句,因为您已经扩展了 Queue<Bachelor>
,我认为没有必要 bachelorQ
那里有引用。您只需将其删除即可。或者甚至更好,只是不要从 Queue<Bachelor>
延伸。只要有可能,您应该更喜欢组合而不是继承。
关于java - 当项目排队到队列对象上时,队列对象保持为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22343723/