Which three statements are benefits of encapsulation?



A. Allows a class implementation to change without changing the clients
B. Protects confidential data from leaking out of the objects
C. Prevents code from causing exceptions
D. Enables the class implementation to protect its invariants
E. Permits classes to be combined into the same package
F. Enables multiple instances of the same class to be created safely

題解

選項A,經過封裝過的類別可以保持API接口的一致,就算內部的程式實作有異動,也不需要去更改到其它引用了這個封裝好的類別的程式。舉例來說,某應用程式使用了其它封裝成JAR檔案的函式庫來進行影像處理的計算,而這個函式庫後來又有推出新版本來優化計算的速度。此時若要更新這個應用程式,讓它去使用新版本的函式庫的話,只需要替換JAR檔案即可,不用更改或是重新編譯原先的應用程式。

選項B,封裝可以隱藏程式碼,保護機密的資料外洩。

選項C,封裝無法防止例外的發生。

選項D,封裝可以保護類別的實作程式不被修改。

選項E,封裝觀念和套件並沒有直接的關係。

選項F,封裝與將一個類別實體化出不同物件的安全性並沒有關聯。