【发布时间】:2019-09-16 02:26:05
【问题描述】:
我无法弄清楚如何从我的 ListQueue 类中调用方法“front”。 ListQueue 类实现接口“Queue”,其中还包含“front”作为变量。该方法在 Queue 中是公共的,在 ListQueue 中是受保护的。
当我尝试使用 q1 和 q2 调用 front 时,无法识别该方法。我假设这是因为它是受保护的访问修饰符,因为它可以识别具有公共访问权限的其他方法。如果是这种情况,有没有办法在不将保护更改为公共的情况下解决这个问题?我试图在 ListQueue 的方法上方添加@Override,但说它不会覆盖超类。
public class BaseMerging {
private static Queue mergeQueues(Queue<Comparable> q1, Queue<Comparable> q2) {
Queue<Comparable> ListQueue = new ListQueue<Comparable>();
while (!q1.isEmpty() && !q2.isEmpty()) {
**DOES NOT RECOGNIZE "FRONT" METHOD**
if (!less(q1.*front()*, (q2.*front()*))) {
ListQueue.add(q1.poll());
} else {
ListQueue.add(q2.poll());
}
}
...
}
public class ListQueue<Item> implements Queue<Item> {
protected Item front() {
if(isEmpty())
throw new NoSuchElementException();
return head.getElement();
}
...
}
public interface Queue<Item> {
public Item front() throws NoSuchElementException;
...
}
我认为一个类可以从另一个类访问受保护的方法,只要它在同一个包中,但也许我错了。是不是因为 ListQueue 从 Queue 继承了“front”?请帮忙。
【问题讨论】:
标签: java inheritance interface comparator method-call