【问题标题】:Calling protected method "Front" from ListQueue class, which implements Queue interface从实现 Queue 接口的 ListQueue 类调用受保护的方法“Front”
【发布时间】: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


    【解决方案1】:

    当你重写超类方法时,访问修饰符不能比超类方法更严格。

    您的实现违反了该规则。

    所以你不能用受保护的访问修饰符覆盖公共方法。

    https://docs.oracle.com/javase/tutorial/java/IandI/override.html

    检查修饰符部分。

    【讨论】:

      猜你喜欢
      • 2010-11-17
      • 1970-01-01
      • 2012-06-23
      • 2010-09-21
      • 1970-01-01
      • 2011-06-12
      • 2013-04-07
      • 2013-09-02
      • 2010-09-30
      相关资源
      最近更新 更多