當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Java Observable notifyObservers()用法及代碼示例

Observable類notifyObservers()方法

用法:

    public void notifyObservers();
    public void notifyObservers(Object o);
  • notifyObservers() 方法可在java.util包。
  • notifyObservers() 方法用於在對象發生更改時通知列表中的所有觀察者。
  • notifyObservers(Object o) 方法用於在此對象更改時通知列表中的所有觀察者,稍後將調用 clearChanged() 以表示此對象不再需要更改。
  • 這些方法在通知觀察者時不會拋出異常。
  • 這些是非靜態方法,它可以通過類對象訪問,如果我們嘗試使用類名訪問這些方法,那麽我們也會得到一個錯誤。

參數:

  • 在第一種情況下,notifyObservers() - 它不接受任何參數。
  • 在第一種情況下,notifyObservers(Object o) -Object o- 代表任何類型的對象。

返回值:

在這兩種情況下,方法的返回類型都是void,它什麽都不返回。

範例1:

// Java program to demonstrate the example 
// of notifyObservers() method of Observable

import java.util.*;

// Implement Observers class 
class Observers_1 implements Observer {
    public void update(Observable obj, Object ob) {
        System.out.println("Obs1 is notified");
    }
}

// Implement Observed Class
class Observed extends Observable {
    // Function call with setChanged()
    void notifyObserver() {
        setChanged();

        // By using notifyObservers() method is 
        // to notify all the observers that are
        // implemented
        notifyObservers();
    }
}

public class NotifyObserver {
    // Implement Main Method
    public static void main(String args[]) {
        Observed observed = new Observed();
        Observers_1 obs1 = new Observers_1();
        observed.addObserver(obs1);
        observed.notifyObserver();
    }
}

輸出

Obs1 is notified

範例2:

import java.util.*;

class Observers_2 implements Observer {
    public void update(Observable obj, Object ob) {
        System.out.println("Obs2 is notified:" + ((Float) ob).floatValue());
    }
}

// Implement Observed Class
class Observed extends Observable {
    // Function call with setChanged()
    void notifyObserver1() {
        setChanged();

        // By using notifyObservers() method is 
        // to notify all the observers that are
        // implemented
        notifyObservers();
    }

    void notifyObserver2() {
        setChanged();

        // By using notifyObservers() method is 
        // to notify all the observers that are
        // implemented with the given object
        notifyObservers(new Float(10.0));
    }

}

public class NotifyObserver {
    // Implement Main Method
    public static void main(String args[]) {
        Observed observed = new Observed();
        Observers_2 obs2 = new Observers_2();
        observed.addObserver(obs2);
        observed.notifyObserver2();

    }
}

輸出

Obs2 is notified:10.0


相關用法


注:本文由純淨天空篩選整理自Preeti Jain大神的英文原創作品 Java Observable notifyObservers() Method with Example。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。