无法降低从对象继承的方法的可见性

时间:2015-04-04 15:24:05

标签: java final

我定义了以下两个类:

public abstract class Subject {

    private ArrayList<ClockObserver> clockObserverList = new ArrayList<ClockObserver>();


    public void attach(ClockObserver clockObserver) {
        // begin-user-code
        // TODO Auto-generated method stub
        clockObserverList.add(clockObserver);
        // end-user-code
    }
    public void dettach(ClockObserver clockObserver) {
        // begin-user-code
        // TODO Auto-generated method stub
        clockObserverList.remove(clockObserver);
        // end-user-code
    }

    protected void notify() {
        // begin-user-code
        // TODO Auto-generated method stub
        for(int i= 0; i < clockObserverList.size(); i++)
        {
            clockObserverList.get(i).update();
        }
        // end-user-code
    }
}

public class SystemClock extends Subject {
    private int hour;
    private int minute;
    private int second;
    public void setTime(int hour, int minute, int second) {
        this.hour = hour; 
        this.minute= minute; 
        this.second = second;
        notify();
    }
    public ClockTime getTime() {
         ClockTime clockTime = new ClockTime();
         clockTime.hour = this.hour;
         clockTime.minute = this.minute;
         clockTime.second = this.second;
        return clockTime;
    }
    public void displayTime() {

        System.out.println("Time is :" + this.hour + ":" + this.minute + ":" + this.second);
    }
}

我的通知功能出现以下错误:

Multiple markers at this line
    - Cannot override the final method from Object
    - overrides java.lang.Object.notify
    - Cannot reduce the visibility of the inherited method from 

即使我将其可见性从受保护更改为公开,我仍然会出现以下错误:

Multiple markers at this line
    - Cannot override the final method from Object

你能帮我解决一下这个问题吗?

4 个答案:

答案 0 :(得分:1)

在Java中,每个类都隐式扩展Object类,它定义了一个名为notify的方法。因此,如果在类中创建方法notify,编译器会认为您试图覆盖Object.notify方法,显然不是这种情况。

只需重命名您的方法notify,您应该没问题。

答案 1 :(得分:0)

  1. final方法是无法覆盖的方法。
  2. 您无法覆盖public方法{。}}。

答案 2 :(得分:0)

方法上的final修饰符意味着不能也不能覆盖该方法。因此,您无法覆盖方法notify

关于可见性,你不能隐藏&#34;你重写的方法,无论如何,只要将变量强制转换为超类,它们仍然是可见的。

想象一下:

class A {
  protected String toString() { return "hidden"; } // Will not compile
}
A a = new A();
Object stillA = a; // a is an instance of A, so it is an instance of Object too
stillA.toString(); // This is still accessible, since Object.toString is public

答案 3 :(得分:0)

子类中不能覆盖java中的最终方法。在您的情况下,您尝试覆盖Object类的notify方法,这是不可能的。如果您确实想使用Object类的方法,那么使用其他名称定义一个新方法,编写代码然后在新方法中调用notify。 对于例如

public void notifySubject() {
   for(int i= 0; i < clockObserverList.size(); i++) {
        clockObserverList.get(i).update();
   }
   notify();         
}
相关问题