I am trying to implement a Observer Pattern on Java.
It won't compile because notifyAll()
seems to be the problem here;
Cannot override the final method from Object
but I haven't put any 'final' nor 'static' in the code.
What am I doing wrong here?
import java.util.ArrayList;
import java.util.List;
interface Observer {
void update();
}
interface Subject {
void registerObserver(Observer o);
void deregisterObserver(Observer o);
void notifyAll();
}
// Concrete Class
class User implements Observer {
@Override
public void update() {
System.out.println("Donald Trump just tweeted, you know");
}
}
// Concrete Class
class realDonaldTrump implements Subject {
private boolean hasTweeted = false;
private ArrayList<Observer> followers = new ArrayList<Observer>();
public boolean hasTweetedIn24Hours() {
return hasTweeted;
}
public void donaldTweets(boolean hasTweeted) {
this.hasTweeted = hasTweeted;
notifyAll();
}
@Override
public void registerObserver(Observer o) {
followers.add(o);
}
@Override
public void deregisterObserver(Observer o) {
followers.remove(o);
}
@Override
public void notifyAll() {
for (Observer o: followers)
o.update();
}
}
public class ObserverPatternDemo {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("Hello World");
System.out.println("Observer Pattern Demo");
realDonaldTrump tweeterAcc = new realDonaldTrump();
}
}
By default all classes extend the Object
class which has a final
method named notifyAll()
. Since the method is final
, it cannot be overridden in your class.
public final native void notifyAll(); // in Object class