Problems with Observable

Hi all,

I'm having problems to add an observer to its observable object.

I have the class Foo, which extends Observable and the class ObserveFoo which implements Observer.

At the constructor of ObserveFoo, I have something like:

public ObserveFoo()

{

Foo f =new Foo();

f.addObserver(this);

}

I have a method which is supposed to notify those observers, so I do:

publicvoid updateObservers(Object event)

{

setChanged();

notifyObservers(event);

System.out.println(countObservers());

}

The problem is that this println is printing 0!

I think I'm having problems with some references here. Could anybody give me a light on this?

[1006 byte] By [Valerianoa] at [2007-11-27 5:43:05]
# 1
I find it odd that you construct a Foo object -- the Observable -- as a local variablein the obverver's constructor. How do you even send it messages?
Hippolytea at 2007-7-12 15:22:21 > top of Java-index,Java Essentials,New To Java...
# 2

Hi Valeriano,

I've been looking to your code, which doesn't seems to be logic. Because, the point of Foo, the Observable, is to notify the Observer. So creating an observable in the observer is not logic.

Let me give you a code example:

Foo.java

public class Foo extends Observable {

public void doSomething() {

this.setChanged();

System.out.println("foo observers: " + this.countObservers());

this.notifyObservers();

}

public static void main(String arg[]) {

Foo foo = new Foo();

FooObserver checkFoo = new FooObserver();

foo.addObserver(checkFoo);

foo.doSomething();

}

}

FooObserver.java

public class FooObserver implements Observer {

public void update(Observable o, Object arg) {

System.out.println(o + " updated, " + arg);

}

}

When i run this code, i'll get this output:

foo observers: 1

Foo@42e816 updated, null

Hope i've helped you.

BeanDippera at 2007-7-12 15:22:21 > top of Java-index,Java Essentials,New To Java...
# 3
Are you playing with the observer interface to learn it, or are you trying to use it for some purpose?If the latter, then how are you trying to use this?
petes1234a at 2007-7-12 15:22:21 > top of Java-index,Java Essentials,New To Java...
# 4
Petes,i think he is trying to learn the usage of Observables, that's why he posted in New to Java, and called the objects Foo.
BeanDippera at 2007-7-12 15:22:21 > top of Java-index,Java Essentials,New To Java...