Reference Types CSCI1302 Lakshmish Ramaswamy Reference Variables Java
Reference Types CSCI-1302 Lakshmish Ramaswamy
Reference Variables • Java supports 8 primitive types • All other types are reference types • Reference variable stores the memory address of where an object resides • Null to indicate the variable is not referencing any object
Reference Example
Operations • Type conversion • Accessing internal field/method (dot operator) • instanceof operator for verifying the type of a stored object • Primitive operations are not allowed
Assignment Operator on References
Objects in Java • Instance of a non-primitive type • Reference variables store the memory location of the objects – Actual objects stored somewhere else – Object variables are a “name” for the memory location
dot Operator • Accessing the internal field of an object • Invoking methods on the object double Area = the. Circle. area(); radius = the. Circle. radius; • Null Pointer exception if variable is storing a null reference
Declaration of Objects Button b; b. set. Label(“No”); p. add(b); Button b; b = new Button(); b. set. Label(“No”); p. add(b); Button b = new Button(“No”); p. add(b);
Garbage Collection • Java destroys all objects that are not referenced • Guarantees that object will be maintained if it is possible to access the object • No guarantees on when an unreferenced object will be destroyed
“=“ Operator • lhs = rhs means the value of rhs will be copied to lhs • For objects memory location will be copied – lhs and rhs refer to the same object Button no. Button = new Button (“no”); Button yes. Button = no. Button; yes. Button. set. Label(“No”); p. add(no. Button); p. add(yes. Button);
Parameter Passing • Value passed for objects is the reference • So any method called is reflected upon the original copy public static void clear. Button (Button b) { b. set. Label(“No”); B = null; }
Illustration of Parameter Passing
Project 1 Information CSCI-1302
Project Expectations • Not using OO principles in the first assignment • Will be done in a “procedural” fashion. • Global variables should to be static and placed outside of main(). • All methods should be static methods! Otherwise, must instantiate an object!
File/Class Name • Your program should be named Mine. Sweeper. java • This means you have to create a class also called Mine. Sweeper in this file. – public class Mine. Sweeper
Static Final Variables (p. 20) • Static Final variables are constants. – Ex. static final double PI = 3. 14; • Should be declared in all CAPS • Declared outside of any function, but within the class declaration. • These should be used whenever possible – I. e. NUM_ROWS, NUM_COLS for matrix dimensions.
The Board • The board should be a 10 x 10 matrix of integers. – Int[][] board = new int[NUM_ROWS][NUM_COLS] • Should store, COVERED, FLAGGED, or the integer representing # of adjacent mines.
- Slides: 17