How to use the non-static method (observer's method) in principle static

advertisements

want to use non static method in static main, but i cant. I know this problem but, because i use INotificationObserver, i cant make registerObserver as static. So i could solve my problem.

How can i solve this problem ?? Thanks .

non-static variable this cannot be referenced from a static context

Test

   public class PushTest implements INotificationObserver{
   NotificationService ns = NotificationService.getInstance(); 

    public static void main(String[] args) {
        try {
            ns.registerObserver(this); // How can i register ???

Interface

public interface INotificationSubject {
    public  void registerObserver(INotificationObserver o);
    public void removeObserver(INotificationObserver o);
    public void notifyObserver(PushedNotification notification);
}

*NotificationService *

public class NotificationService implements  INotificationSubject{

    protected static final Logger logger = Logger.getLogger(NotificationService.class);
    private volatile static NotificationService uniqueFactory;
      private ArrayList observers;

    private NotificationService() {
      observers = new ArrayList();
    }
    public static NotificationService getInstance() {
        if (uniqueFactory == null) {
            synchronized (NotificationService.class) {
                if (uniqueFactory == null) {
                    uniqueFactory = new NotificationService();
                }
            }
        }
        return uniqueFactory;
    }

    public static INotification GetNotificationObject(DeviceTypes Types) {
        INotification messageSender = null;

        if (Types == Types.IOS) {
            messageSender = new IosNotification();
        }

        return messageSender;
    }

    public void registerObserver(INotificationObserver o) {
        observers.add(o);
    }

    public void removeObserver(INotificationObserver o) {
        int i =
                observers.indexOf(o);
        if (i >= 0) {
            observers.remove(i);
        }
    }

    public void notifyObserver(PushedNotification notification) {
        for (int i = 0; i < observers.size(); i++) {
            INotificationObserver observer = (INotificationObserver) observers.get(i);
            observer.update(notification);
        }
    }

    public void messageSendInfo(PushedNotification notification) {
        notifyObserver(notification);
    }

    public void showSentInfo(PushedNotification notification) {
        messageSendInfo(notification);
    }
}


You need an instance:

INotificationObserver ino = new PushTest();
ns.registerObserver(ino);

Therefor, you don't need the ns attribute.