Search code examples
javastaticobservableobservers

Java AddObserver(this) when in static main


So I have a function declared likepublic class Main implements Observer{} inside i have the main function public static void main(String[] args) {} and inside it, I'd like to do this ObservableClass.addObserver(this). But since the main is static I'm not able to do that, and adding a method to the Main class won't fix the problem either since it will be called from a static function anyways. Basically I want the Main class to be an observer and implement a method update(). Does someone know a way to implement this? Thanks.


Solution

  • It should go something like this:

    public class Main implements Observer {
    
        @Override
        public void update(Observable o, Object arg) {
            // ...
        }
    
        public static void main(String[] args) {
            // ...
            observable.addObserver(new Main());
        }
    }
    

    The main method would be better to move to another class, whose only job is to start the main application. Having a main method that starts the application inside an Observer implementation looks suspiciously like a violation of the single responsibility principle.

    In other words, Main should not implement Observer. It should be another class that implements Observer. The Main class should have just a main method, configure and launch the application, and do nothing else.