Java Reference
In-Depth Information
< Day Day Up >
Puzzle 53: Do Your Thing
Now it's your turn to write some code. Suppose that you have a library class called
Thing
whose
sole constructor takes an
int
parameter:
public class Thing {
public Thing(int i) { ... }
...
}
A
Thing
instance provides no way to get the value of its constructor parameter. Because
Thing
is a
library class, you have no access to its internals, and you can't modify it.
Suppose that you want to write a subclass called
MyThing
, with a constructor that computes the
parameter to the superclass constructor by invoking the method
SomeOtherClass.func()
. The
value returned by this method changes unpredictably from call to call. Finally, suppose that you
want to store the value that was passed to the superclass constructor in a final instance field of the
subclass for future use. This is the code that you'd naturally write:
public class MyThing extends Thing {
private final int arg;
public MyThing() {
super(arg = SomeOtherClass.func());
...
}
...
}
Search WWH ::
Custom Search