2

When I read about "In How many ways we can create an Object in java".

I found four way:

  1. Creation of Object using new Operator.
  2. Cloning
  3. Serialization
  4. Reflection.

With new and reflection, I am fine with these two methods.

My Question is:

Why do people consider cloning and serialization as different ways of creating an Object?

Jeremy
  • 22,188
  • 4
  • 68
  • 81
Sunny Gupta
  • 6,929
  • 15
  • 52
  • 80
  • Marko's answer below explains very well why people consider "cloning and serialization" as different from "new and reflection". They are different from each other of course, because if you want to add your own magic to VM magic you have to do different things. – Miserable Variable May 10 '12 at 19:42

2 Answers2

7

The very important point here is that in object deserialization there is no constructor involved in the process -- that's why it is a distinct way to create an object. This is also true of cloning -- the method Object.clone creates a new object by JVM magic, again not involving any constructors. There is in fact much greater difference between these two ways on the one hand and new and reflection on the other, since reflection is just a slightly different way to invoke the plain-vanilla object instantiation involving a specific constructor.

Marko Topolnik
  • 195,646
  • 29
  • 319
  • 436
1

When you clone an object, that means that you are dealing with something that lies in a different part of memory from the original object. Yes, they might have the same properties, but they are two different pointers with two different blocks of memory.

When you unserialize an object then an object exists which did not exist before. Even if you serialize and then immediately unserialize, it will exist independently from the original object.

cwallenpoole
  • 79,954
  • 26
  • 128
  • 166