Some Notes on Objects (cleaned up from Week 3 lecture)

0. Object and Reference

  1. First, the term "object" needs to be clarified.  An "object" in Java technically consists of two entities: (1) an object, which is an instantiation of a class (created by 'new'), and (2) a reference to the object.  For example, a line
    String s1 = new String("abc");

     creates the following picture.

                

    A reference is said to "refer to" (or "point to") the object it points to.

     

  2. Since a reference and an instantiated object are different entities, we can talk about references only, without instantiated objects.  But the terminology is still confusing because a reference, whether or not it points to an instantiated object, is declared with the type/class of the instantiated object (before an object is instantiated).

    For example, if we break the line above into 2 lines,

        String s1;

    At this point, we only have a reference.  This reference points to nowhere, that is, null.

     

    Then in the next line we instantiate an object by new.

        s1 = new String("abc");

    Now the picture becomes:

     

  1. In computer memory, the object part is created in the heap, and the reference part is in the program/stack memory.

     

 

 

 


1. Objects are always created/instantiated by 'new'


2. Objects do not have to be destroyed/deallocated

Scope Issue:


3. Object equality vs. Reference equality