Software Development CSCI-1302

Download Report

Transcript Software Development CSCI-1302

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 = theCircle.area();
radius = theCircle.radius;
• Null Pointer exception if variable is storing
a null reference
Declaration of Objects
Button b;
b.setLabel(“No”);
p.add(b);
Button b;
b = new Button();
b.setLabel(“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 noButton = new Button (“no”);
Button yesButton = noButton;
yesButton.setLabel(“No”);
p.add(noButton);
p.add(yesButton);
Parameter Passing
• Value passed for objects is the reference
• So any method called is reflected upon the
original copy
public static void clearButton (Button b)
{
b.setLabel(“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
MineSweeper.java
• This means you have to create a class
also called MineSweeper in this file.
– public class MineSweeper
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 10x10 matrix of
integers.
– Int[][] board = new
int[NUM_ROWS][NUM_COLS]
• Should store, COVERED, FLAGGED, or
the integer representing # of adjacent
mines.