When I read about "In How many ways we can create an Object in java".
I found four way:
Creation of Object using new Operator.
Cloning
Serialization
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?
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.
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.
Related
I was reading about the cloning in Java, how to make shallow/deep copies of object etc.
I was wondering why do I need to create object clones in Java? Any real time examples could be helpful in understanding.
Having a cloned copy of something means you can have "before" and "after" versions. You can leave the original alone while you test something out with a copy. You can provide undo by simply reverting to the original version.
Quite often you want to use immutable objects, in which case cloning is an essential part of your code. If for example you have an immutable object that has a list or array type field, your getter should always return a clone of the list or array to preserve immutability.
The other typical use case is when you want "transactional" modifications, when you call several state changing methods but only want the result to be visible if all of them are successful.
A concrete example of cloning is the:
prototype design pattern
As Cloning itself says Duplicate copy of something, so In java when we say cloning of object it means to create or have another same object of existing one.
When we do cloning? when we saw that the creating new object every time is time consuming or we need new object having same or little bit difference w.r.t all ready created object, then we use cloning.
Cloning are of 3 types in java
Shallow copy
Deep copy
cloning
Shallow copy
Shallow copy is the process in which the state of the object is copied to another object, but both the objects point to the same reference in heap area.
Deep Copy
In Deep Copy, two separate objects are created and in deep copy. In this each field of one object is copied to another object.
Now third category to overcome this difficulty in java is the concept of cloning.
Cloning in java is done by implements Cloneable interface. Cloneable is marker interface.
For more deep knowledge on cloning Refer : Cloning in java
You may use a deep cloned copy of your object because you may need a partial result in some method which you would like to use later.
As a way to help preserve encasulation (and therefore make you code more robust), you could clone objects before returnng them from a getter. For example, a getDate method might clone a date field before returning to the caller.
`What's the 'canonical table?I can't find any description of it.Can anyone provide a example?'
Are you reading Java Performance Tuning? I saw those concepts in there.
A canonical object means an object with a single reference pointed to it, with no copies holding the same state possible.
The activity of replacing multiple copies of an object with just a few objects is often referred to as canonicalizing objects.
For example Boolean, could have been canocalized, but it were not because new objects can be created with new, thus it's possible to create more than one instance with the same state.
A Canonical Lookup Table is some sort of cache containing references to those canonical object pool.
Put another way, you create a new kind of object by making a package containing existing objects. Thus, you can build complexity into a program while hiding it behind the simplicity of objects.
from Thinking in Java
Are not all objects independent of each other in Java? Is it possible to create a super object from different objects?
EDIT:
Alan Kay summarized five basic characteristics of Smalltalk way before Java was around. This is one of the characteristics of an OOP according to him. I was wondering if it is still valid for java.
I think you have to distinguish two separate concepts:
In memory each object in Java is a separate entity with its own set of memory (and I believe Smalltalk worked the same way). It can reference other objects, which are held in their own memory, but not "contain" other objects within its memory.
Conceptually, there are objects that "belong" to other objects in some way. For example the char[] holding the data of a String is technically a separate object, but the only other object referencing it is the String (and possibly other String instances, but let's ignore that at the moment). In this sense, the String contains the char[].
An object can't contain other objects directly in Java - but it can certainly hold references to other objects. I suspect that's what the author is trying to get across.
So if a Customer object knows about the address, phone number, list of orders, name etc, those would all be separate objects... but instead of having to manage all of those explicitly, the user of a Customer object just keeps a reference to the object, and accesses the rest of the data via that single object.
Is there any reason why an array in Java is an object?
Because the Java Language Specification says so :)
In the Java programming language arrays are objects (§4.3.1), are dynamically created, and may be assigned to variables of type Object (§4.3.2). All methods of class Object may be invoked on an array.
So, unlike C++, Java provides true arrays as first-class objects:
There is a length member.
There is a clone() method which overrides the method of the same name in class Object.
Plus all the members of the class Object.
An exception is thrown if you attempt to access an array out of bounds.
Arrays are instanciated in dynamic memory.
Having arrays be objects means that you can do operations with them (e.g., someArray.count('foo')) instead of just doing it against them (e.g., count(someArray, 'foo')), which leads to more natural syntax.
Another point is that objects are mutable and are passed by reference. In arrays there aren't any fields/methods that you can use to change "properties" of the array, but you sure can mutate the element values. And the benefits of passing arrays by reference are pretty obvious (though functional programmers probably wish Java had immutable lists passed by value).
Edit: forgot to mention. In the period before autoboxing, it was helpful to be able to store arrays in collections, write them to ObjectStreams etc.
Probably because they wanted to get as close as possible to making everything an object. Native types are there for backward compatibility.
So that they get all the benefits thereof:
getHashCode()
toString()
etc.
And arrays aren't 'primitive', so if they can't be primitive, they must be objects.
I'm not sure about the official reason.
However, it makes sense to me that they are objects because operations can be performed on them (such as taking the length) and it made more sense to support these operations as member functions rather than introduce new keywords. Other operations include clone(), the inherited operations of object, etc. Arrays are also hashable and potentially comparable.
This is different from C (and native arrays in C++), where your arrays are essentially pointers to a memory offset.
In Java, an array IS AN Object. My question is... is an Object constructor called when new arrays is being created? We would like to use this fact to instrument Object constructor with some extra bytecode which checks length of array being constructed. Would that work?
Per the JVM spec: "Arrays are created and manipulated using a distinct set of instructions." So, while arrays are instances of Objects, they aren't initialized the same way that other objects are (which you can see if you scroll up from that link anchor).
As far as the Java Language Specification is concerned, although both use the new keyword, Class Instance Creation Expressions and Array Creation Expressions are different forms of expression, each with its own rules. The description of Array Creation Expressions does not mention calling a constructor.
I don't think so because you can not derive a native array to overridethe constructor
You can use byte code manipulation to place the check where ever a new array is created.
Nope. I found this on the AspectJ mailing list: http://dev.eclipse.org/mhonarc/lists/aspectj-users/msg02975.html.
You probably ask about arrays for a reason, but if you can, why not switch to the collection classes. That will give you lots of opportunity to intercept and do validations.