Computer Programming I Instructor: Greg ShawCOP 2210 Constructing ObjectsThe new Operator, Objects, Object Variables, and Object ReferencesI. Constructing (“Creating”) Objects- To construct or create a new object, we use the new operator- Syntax: new class-name( parameter(s) )class-name is the name of a class from the Java library or ofa programmer-defined classparameter(s) - aka: “construction parameters” - are the valuesused to initialize the instance variables of the object (i.e.,to set the “state” of the object)- Example: new Rectangle(10,20,30,20) - Execution: the new operator calls a special method called aconstructor - which creates a new object, using the parameterspassed to initialize its instance variables - and returns areference to the new object- The object reference returned by new is usually stored in anobject variable, e.g.Rectangle box = new Rectangle(10,20,30,20) ;Note that this statement does three things:1. Declares a Rectangle object-variable called box2. Calls the Rectangle class constructor to create a newRectangle object (with x=10, y=20, width=30, andheight=20)3. Assigns the object reference returned to the variable box- As with primitive-type variables (int and double) the variabledeclaration and the assignment may be done separatelyRectangle box ;box = new Rectangle(10,20,30,20) ;II. Objects vs. Object References- Consider again a statement such asRectangle box = new Rectangle(10,20,30,20) ;What is stored in object-variable box is not the objectitself, but a reference to it A reference to an object is the actual address of the objectin memory- Since the contents of an object variable is a reference to theobject and not the object itself, we say that an object-variable“refers to” an object, or “points to” an object.- Object variables are also known as pointers- This is in contrast to primitive-type variables, which store theactual values and not their addresses, e.g.,int luckyNumber = 37 ;luckyNumber contains the value 37 and not the address of somememory location containing a 37 See illustrations on the board in class In practice, many programmers refer to the object-variable as“the object.” There is no harm in this, but it is crucial toour understanding of how OOP works that we realize that theobject-variable is not the object. It is a variable thatstores a reference to the object (i.e., the address of theobject). It is a pointer to the object, through which wecontrol the object.III. The null Reference- In Java, all object variables are automatically initialized tonull- null – which is a Java keyword - is a special value meaning “notpointing to any object”- So the object variable declarationRectangle shoebox ; // automatically initialized to nullis the same asRectangle shoebox = null ; // explicit initialization Any attempt to “dereference” a null pointer (i.e., call a methodfor an object variable that is not pointing to an object) willthrow a
View Full Document