Java Reference
In-Depth Information
Value Semantics (Value Types)
A system in which values are stored directly and copying is achieved by
creating independent copies of values. Types that use value semantics are
called value types.
Reference Semantics (Reference Types)
A system in which references to values are stored and copying is achieved
by copying these references. Types that use reference semantics are called
reference types.
It will take us a while to explore all of the implications of this difference. The key
thing to remember is that when you are working with objects, you are always work-
ing with references to data rather than the data itself.
At this point you are probably wondering why Java has two different systems. Java
was designed for object-oriented programming, so the first question to consider is
why Sun decided that objects should have reference semantics. There are two pri-
mary reasons:
Efficiency. Objects can be complex, which means that they can take up a lot of
space in memory. If we made copies of such objects, we would quickly run out of
memory. A String object that stores a large number of characters might take up
a lot of space in memory. But even if the String object is very large, a reference
to it can be fairly small, in the same way that even a mansion has a simple street
address. As another analogy, think how we use cell phones to communicate with
people. The phones can be very tiny and easy to transport because cell phone
numbers don't take up much space. Imagine that, instead of carrying around a set
of cell phone numbers, you tried to carry around the actual people!
Sharing. Often, having a copy of something is not good enough. Suppose that
your instructor tells all of the students in the class to put their tests into a certain
box. Imagine how pointless and confusing it would be if each student made a
copy of the box. The obvious intent is that all of the students use the same box.
Reference semantics allows you to have many references to a single object, which
allows different parts of your program to share a certain object.
Without reference semantics, Java programs would be more difficult to write.
Then why did Sun also decide to include primitive types that have value semantics?
The reasons are primarily historical. Sun wanted to leverage the popularity of C and
C++, which had similar types, and to guarantee that Java programs would run
quickly, which was easier to accomplish with the more traditional primitive types. If
Sun had a chance to redesign Java today, the company might well get rid of the prim-
itive types and use a consistent object model with just reference semantics.
 
Search WWH ::




Custom Search