Recently had an interviewer ask to define the difference between objects and primitives. Seemed like an odd question considering that all languages begin with a primitive. How would you have answered this question?
I should also note that this interview was for a front-end development position so the language (I assume) he was referring to was JavaScript.
A primitive is a data type that is composed of no other data types and can not be broken down any further. It is like the atoms in the programming scenario. I say atom because atom is a basic unit of matter and there is nothing that can be derived from it.
I mean, an int in C can not be broken down into smaller data type. An object, on the other hand can be thought of a molecule, consisting of more than one primitive type. For example, string comes as part of the C++ standard library; however, it is an object and it is composed of smaller data types internally and contains methods.
It is important to note that not all object-oriented languages are class based (eg. Javascript) You can not define a class in Javascript, so an object is quite different here. Even though everything in Javascript is an object (Ruby also), the Number object is really a wrapper for an internal primitive.
From Java perspective:
- A primitive is not composed of other data types. Where as an object can be and generally is.
- Primitives are passed by value, i.e. a copy of the primitive itself is passed. Whereas for objects, the copy of the reference is passed, not the object itself.
- Primitives are independent data types, i.e. there does not exist a hierarchy/super class for them. Whereas every Object is descendent of class "Object".
- Every object has some default methods of itself, which it inherits from the class Object (e.g. toString(), clone(), wait(), notify(), notifyAll(), etc.). The primitives does not have any method associated with themselves.
- Primitives are immutable, they can be used as so without any special care. Whereas for objects, special care needs to be taken, they are not immutable by default.
- With objects, there are two types of copies, Shallow and Deep. There is a significant difference between them. So the choice depends on how do we intend to use them. With primitives, there is no such difference, everything is by default deep copy only.
I think primitive cannot divided any more like int, string (such as built-in data type) . On the other way, object can divide into small pieces like array, structure.
I am just a student and this is my opinion.
If you think my answer is wrong, you can correct me.
Thanks
来源:https://stackoverflow.com/questions/8643276/object-vs-primitive