gpt4 book ai didi

java - 《Java 编程语言》第四版练习 3.3

转载 作者:行者123 更新时间:2023-12-02 03:36:44 26 4
gpt4 key购买 nike

我花了很长时间思考这个练习,但我无法理解这个问题的含义。本节讨论扩展类以及从扩展类构造对象时事情发生的顺序。

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:

  1. Invoke a superclass's constructor.
  2. Initialize the fields using their initializers and any initiation blocks.
  3. 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?

代码:

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;
}
}

最佳答案

我认为这个练习是为了说明实例化 Y 时会发生什么,即 Y y = new Y();。我认为他们解释得不太好,因为第 2 项没有描述它意味着什么字段(类或父类(super class))。如果将代码放入调试器并在不同的语句处停止,则执行上述语句时会发现以下执行顺序:

  1. 调用 Y 的构造函数,即执行控制传递到 Y 构造函数的开头
  2. 调用 X 的构造函数
  3. X 的变量初始化已执行,因此 xMask 得到 0x00ff。
  4. X 的构造函数语句被执行,因此 fullMask 获取 xMask 值。
  5. Y 的变量初始化完成,因此 yMask 得到 0xff00;
  6. Y 的构造函数语句被执行,因此 fullMask 得到 fullMask 与 yMask 的结果。

所以这将是预期的行为 - 无论 X 对变量等做什么,都是在 Y 获得任何控制权之前完成的; Y 不应该“知道”X 是如何实现的,它只是应该使用 X(希望)记录下来的行为。

我希望这对您有所帮助。我不喜欢这本书将这种行为描述为“问题”;我在这里没有看到“问题”。为了编写扩展 X 的 Y,您需要了解影响您的 X 行为的外部可见部分。在本例中,X 为 fullmask 提供了一个特定值,您可以在 Y 构造函数中使用该值。

关于java - 《Java 编程语言》第四版练习 3.3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37372591/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com