練習問題3.2(改)
アドバイスを頂き、情報表示用のメソッドをabstractメソッドにし、
表示用に初期化ブロックを使ってみました。
初期化ブロックは始めて使うのでこんな感じでいいのか少し不安
X.java
public abstract class X { { traceStep(); } protected int xMask = 0x00ff; { traceStep(); //Xのフィールドの初期化後 } protected int fullMask; private static int step=0; public X(){ fullMask = xMask; traceStep(); //Xのコンストラクタの実行後 } public int mask(int orig){ return (orig & fullMask); } public abstract void traceStep(); public int getStep(){return step;} public void addStep(){step++;} public int getXMask(){return xMask; } public int getFullMask(){return fullMask; } }
Y.java
public class Y extends X{ protected int yMask = 0xff00; { traceStep(); //Yのフィールドの初期化後 } public Y(){ fullMask |= yMask; traceStep(); //Yのコンストラクタの実行後 } public void traceStep(){ System.out.printf("%-2d 0x%04x 0x%04x 0x%04x \n", super.getStep(), super.getXMask(),yMask, super.getFullMask()); super.addStep(); } public int getYMask(){return yMask; } public static void main(String[] args) { System.out.printf("%2s %-6s %-6s %-6s \n", "no","xMask","yMask","fullMask"); Y y = new Y(); } }
実行結果
no xMask yMask fullMask
0 0x0000 0x0000 0x0000
1 0x00ff 0x0000 0x0000
2 0x00ff 0x0000 0x00ff
3 0x00ff 0xff00 0x00ff
4 0x00ff 0xff00 0xffff