Primitive Types vs. Reference Types
Data types in Java are divided into two categoriesprimitive types and reference types (sometimes called nonprimitive types). The primitive types are boolean, byte, char, short, int, long, float and double. All nonprimitive types are reference types, so classes, which specify the types of objects, are reference types.
A primitive-type variable can store exactly one value of its declared type at a time. For example, an int variable can store one whole number (such as 7) at a time. When another value is assigned to that variable, its initial value is replaced. Primitive-type instance variables are initialized by defaultvariables of types byte, char, short, int, long, float and double are initialized to 0, and variables of type boolean are initialized to false. Programmers can specify their own initial values for primitive-type variables. Recall that local variables are not initialized by default.
Programs use variables of reference types (normally called references) to store the locations of objects in the computer's memory. Such variables are said to refer to objects in the program. Objects that are referenced may each contain many instance variables and methods. Line 14 of Fig. 3.8 creates an object of class GradeBook, and the variable myGradeBook contains a reference to that GradeBook object. Reference type instance variables are initialized by default to the value nulla reserved word that represents a "reference to nothing." This is why the first call to getCourseName in Fig. 3.8 returned nullthe value of courseName had not been set, so the default initial value null was returned. The complete list of reserved words and keywords is listed in Appendix C, Keywords and Reserved Words.
A reference to an object is required to invoke (i.e., call) the object's methods. In the application of Fig. 3.8, the statements in method main use the variable myGradeBook to send messages to the GradeBook object. These messages are calls to methods (like setCourseName and getCourseName) that enable the program to interact with the GradeBook objects. For example, the statement (in line 23)
myGradeBook.setCourseName( theName ); // set the course name
uses myGradeBook to send the setCourseName message to the GradeBook object. The message includes the argument that setCourseName requires to perform its task. The GradeBook object uses this information to set the courseName instance variable. Note that primitivetype variables do not refer to objects, so such variables cannot be used to invoke methods.
Software Engineering Observation 3.4
A variable's declared type (e.g., int, double or GradeBook) indicates whether the variable is of a primitive or a reference type. If a variable's type is not one of the eight primitive types, then it is a reference type. For example, Account account1 indicates that account1 is a reference to an Account object). |