SCJP 1.6版考題 053

出自 陳富國維基館
於 2013年3月30日 (六) 07:17 由 Ikk (對話 | 貢獻) 所做的修訂 (新頁面: Insert six modifiers into the code such that it meets all of these requirements: 1. It must be possible to create instances of Alpha and Beta from outside the packages in which they ...)
(差異) ←上個修訂 | 最新修訂 (差異) | 下個修訂→ (差異)
前往: 導覽搜尋
Insert six modifiers into the code such that it meets all of these requirements:
1. It must be possible to create instances of Alpha and Beta from outside the packages in which they are defined.
2. When an object of type Alpha (or any potential subclass of Alpha) has been created, 
   the instance variable alpha may never be changed.
3. The value of the instance variable alpha must always be "A" for objects of type Alpha.

SCJP53-1.png

解答


Ans:
SCJP53-2.png

解說:

此題的需求
  1.必須要能從套件外部建立Alpha與Beta的物件ß 這表示Alpha與Beta必須是public,而且其建構子也必須為public
  2.Alpha物件變數永遠不被改變
  3.Alpha物件變數必須遠是字串”A”
要滿足2與3必須控制外界不能改變Alpha的物件變數,也就是將alpha變數設為private
Beta建構子有呼叫Alpha(String),所以這個建構子必須設成Beta可以存取,也就是設成protected