Introduction to Object

Download Report

Transcript Introduction to Object

Introduction to Java Objects
CSIS 3701: Advanced Object Oriented Programming
Object-Oriented Programming
Object
“Client
programmer”:
Programmer who
uses class in their
own code
Methods to
access member
variables
Member variables
representing
Constructors to
current state
set initial value
of object
of member
variables
Basic Object Syntax
• Declaring objects:
classname objectname;
• Constructing objects:
objectname = new classname(params);
• Calling object methods:
returntype =
objectname.methodname(params);
Basic Object Syntax
• Example
object in Stack class
Stack s;
constructed (no parameters)
s = new Stack();
s.push(“Larry”);
method calls on this
s.push(“Curley”);
stack object
if (!s.empty()) {
System.out.println(s.pop());
}
Objects and Memory
• Objects represented as a reference to memory
– Must be dynamically allocated
•
Stack s;
37A4
s 37A4
Memory for s’s attributes (stack contents, etc.)
Arrays in Java
• Arrays are treated as reference types
• Must be allocated with new
int[] A;
A = new int[5];
A refers to null
A refers to newly allocated
array of 5 ints (160 bits)
• Arrays have object-like attributes
– Example: length
Evaluates to 5
int total = 0;
for (int i = 0; i < A.length; i++)
total += A[i];
Memory Allocation
• Initially s points to null
– Will get NullPointerException if attempt to use
• Must allocate memory with new
s = new Stack();
– Allocates memory for object
(size of state variables)
– Invokes constructor
(initializes state variables)
– Returns memory location for storage in reference s
Memory Management
• Avoid using assignment with objects:
Stack s1 = new Stack();
Stack s2 = new Stack();
s2 = s1;
37A4
Now refer to
same location
in memory
s1 37A4
4E15
s2 37A4
• Many classes have clone method that create copy of
any state variables
– s2 = s1.clone();
References and Comparison
• Example:
Stack s1 = new Stack();
Stack s2 = new Stack();
s1
s2
if (s1 == s2) {…}
Evaluates to false since s1
and s2 are different objects
• Better to use built-in equals method:
if (s1.equals(s2)) {…}
– Default version works like ==
– Often designed to do “expected” comparison for class
– String version does character-by-character comparison
Memory Deallocation
37A4
t1
4E15
t2
Memory at location 4E15
inaccessible – should be
reallocated for future use
• Manual deallocation (delete in C++):
– Potentially dangerous
delete t2;
t1.setText(“Barney”);
• “Garbage collection” in Java
– JVM periodically scans sandbox for unreachable
memory and reallocates back to OS
– Safer, but takes time
 tradeoff