2009年2月9日 星期一

第53題

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.

Code
package alpha;
Place here class Alpha{
Place here String alpha;
Place here Alpha(String a){alpha = a;}
Place here Alpha(){this("A"); }
}
package beta;
Place here class Beta extends alpha.Alpha{
Place here Beta(String a){super(a);}
}

Modifiers
private
protected
public
答案:

package alpha;
public class Alpha{
private String alpha;
public Alpha(){this("A");}
protected Alpha(String a){alpha = a;}
}
package beta;

public class Beta extends alpha.Alpha{
public Beta(String a){super(a);}
}
參考:6-5 繼承、7-3 存取修飾詞的使用
-------------------------------------------------
1. It must be possible to create instances of Alpha and Beta from outside the packages in which
they are defined.
//套件外部要能建立Alpha and Beta 類別的物件,代表Alpha and Beta的存取修飾詞的類別
要為public 且 Beta的建構式要為public
2. When an object of type Alpha (or any potential subclass of Alpha) has been created, the

instance variable alpha may never be changed.
//如果要建立Alpha 物件或Alpha 子類別的物件,則實體變數Alpha 不能改變,表示Alpha 的值不能被外部改變,因此要宣告成private 只能開放讓建構式存取,因此建構式要定為protected
3. The value of the instance variable alpha must always be "A" for objects of type Alpha.
要建立alpha 物件且實體變數alpha 值要恆為A,也就是說Alpha(){this("A");} 這一個建構式要開放給外部存取

沒有留言:

張貼留言