Presentation is loading. Please wait.

Presentation is loading. Please wait.

Introduction to Java Objects CSIS 3701: Advanced Object Oriented Programming.

Similar presentations


Presentation on theme: "Introduction to Java Objects CSIS 3701: Advanced Object Oriented Programming."— Presentation transcript:

1 Introduction to Java Objects CSIS 3701: Advanced Object Oriented Programming

2 Object-Oriented Programming “Client programmer”: Programmer who uses class in their own code Methods to access member variables Constructors to set initial value of member variables Member variables representing current state of object Object

3 Basic Object Syntax Declaring objects: classname objectname; Constructing objects: objectname = new classname(params); Calling object methods: returntype = objectname.methodname(params);

4 Basic Object Syntax Example Stack s; s = new Stack(); s.push(“Larry”); s.push(“Curley”); if (!s.empty()) { System.out.println(s.pop()); } object in Stack class constructed (no parameters) method calls on this stack object

5 Objects and Memory Objects represented as a reference to memory –Must be dynamically allocated Stack s; s 37A4 Memory for s ’s attributes (stack contents, etc.) 37A4

6 Arrays in Java Arrays are treated as reference types Must be allocated with new int[] A; A = new int[5]; Arrays have object-like attributes –Example: length int total = 0; for (int i = 0; i < A.length; i++) total += A[i]; A refers to null A refers to newly allocated array of 5 ints (160 bits) Evaluates to 5

7 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

8 Memory Management Avoid using assignment with objects: Stack s1 = new Stack(); Stack s2 = new Stack(); s2 = s1; Many classes have clone method that create copy of any state variables –s2 = s1.clone(); Now refer to same location in memory s1 37A4 4E15 s2 37A4

9 References and Comparison Example: Stack s1 = new Stack(); Stack s2 = new Stack(); if (s1 == s2) {…} 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 Evaluates to false since s1 and s2 are different objects s1 s2

10 Memory Deallocation 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 t1 37A44E15 t2 Memory at location 4E15 inaccessible – should be reallocated for future use


Download ppt "Introduction to Java Objects CSIS 3701: Advanced Object Oriented Programming."

Similar presentations


Ads by Google