Howdy, I was writing some sample code on serialization and testing out various parts of it. The code below is throwing me for a loop though because it doesnt make sense WHY something is the way it is. It may be a bug but I dont see how. Can somone explain my results?
Below you'll see that I have 6 boxes total. The first 3 which I create new instances of with new main(); The static variable boxes and the constructor of the class increment how many I have. These reference variables should be set each time the constructor is called on a new instance right? With me so far...
Now, we serialize these objects, and save them to a disk file. I read them in a different order back (because the SCJP study guide didnt mention it and I wanted to see if it worked the way I thought (which it did)). Regardless I read these into different "boxes" Box4, Box6 and Box5. Now I NEVER EVER created instances these objects. In fact they are declared as null.
Once the code reads the objects back in, theoretically it's creating an insance and pointing it to boxes 4,5,6. Here is the kicker. If it's creating new Main instances, why is the static variable not being incremented? If you run this code, the number of "boxes" returns 3. But in reality, you have 6 differnt boxes!
If the rule for statics is that it's the same once the class is "loaded" then I should have 6 right? Ok, I know what youre going to say... I cast it to a Main so therefore it's an Object instance not a Main instance. I'm cool with that BUT, if the generic "Object" doesnt contain my methods (not an IS-A) relationship, how did they get there! Ok, one more
System.out.println(Box6 instanceof Main);
I'm sure this is some special serialization thing but I'd like to know how that works. Even if it's not on the SCJP that's just creepy.
I think, if the Class doesnot implement Serializable interface then at the deserialization time, the constructor will be invoked. Here class Main implements Serializable so no need to invoke constructor at the deserialization time.
-------------- Modified Code : to Explain When and when not Constructor will be invoked. --------------
Try to avoid run this and see output and after that remove comment of SCJPParent Class and then run the code.
I hope this will help you little.
I like you because you always keep good, crunchy cereal in your pantry. This tiny ad agrees: