Reputation: 65
I've spent a long time thinking about this exercise and I can't wrap my head around what the question means. The section talks about extended classes and the order in which things take place when an object is constructed from an extended class.
When an object is created, memory is allocated for all its fields, including those inherited from superclasses, and those fields are set to default initial values for their respective types (zero for all numeric types, false for boolean, '\u0000' for char, and null for object references). After this, construction has three phases:
- Invoke a superclass's constructor.
- Initialize the fields using their initializers and any initiation blocks.
- Execute the body of the constructor.
...
Exercise 3.3: If it were critical to set up these masks using the values from the extended class during construction, how could you work around these problems?
Code:
class X {
protected int xMask = 0x00ff;
protected int fullMask;
public X() {
fullMask = xMask;
}
public int mask(int orig) {
return (orig & fullMask);
}
}
class Y extends X {
protected int yMask = 0xff00;
public Y() {
fullMask |= yMask;
}
}
Upvotes: 0
Views: 164
Reputation: 13123
I think the exercise is meant to illustrate what happens when you instantiate Y, i.e. Y y = new Y();
. I don't think they explain it all that well, because item 2 doesn't describe what fields it means (class or superclass). If you put the code into a debugger and stop at the different statements, you find the following order of execution when the above statement is executed:
So this would be the expected behavior - whatever X does with variables, etc., is done before Y gets any control; Y is not supposed to 'know' how X is implemented, it is just supposed to use X as it is (hopefully) documented to behave.
I hope that's a help. I don't like the book's characterization of this behavior as "problems"; I don't see a "problem" here. In order to write Y, which extends X, you need to be aware of the externally visible portion of X's behavior which affects you. In this case, X gives fullmask
a certain value, which you use in your Y constructor.
Upvotes: 2