240 likes | 253 Views
Learn about creating, using, and cleaning up objects in Java programming. Understand the object lifecycle, garbage collection, and finalize method. Explore examples with arrays and object cleanup.
E N D
Lecture 6Object Oriented Programming in Java Language Basics Objects and Data Basics Object Oriented Programming in Java (95-707)Java Language Basics
Today’s Lecture • Trail: Learning the Java Language • Lesson: Object and Data Basics Object Oriented Programming in Java (95-707)Java Language Basics
Objects Life Cycle • Stages • creation • use • cleanup Object Oriented Programming in Java (95-707)Java Language Basics
Creation of an object • Class Declaration (providing name and definition for the object) • instantiation (setting aside memory for the object) • optional initialization (providing initial values for the object via constructors) Object Oriented Programming in Java (95-707)Java Language Basics
Use of an object • We activate the behavior of an object by invoking one of its methods (sending it a message). • When an object receives a message (has one of its methods invoked), it either performs an action, or modifies its state, or both. Object Oriented Programming in Java (95-707)Java Language Basics
Cleanup • What happens to all the objects that are instantiated? • When an object is no longer needed, we simply forget it. Eventually, the garbage collector may (or may not) come by and pick it up for recycling • What is being recycle? • Precious memory allocation Object Oriented Programming in Java (95-707)Java Language Basics
Cleanup Approach • The good news • if things work as planned, the Java programmer never needs to worry about returning memory to the operating system. This is taken care of automatically by a feature of Java known as the garbage collector. • The bad news • Java does not support anything like a destructor that is guaranteed to be called whenever the object goes out of scope or is no longer needed. Therefore, other than returning allocated memory, it is the responsibility of the programmer to explicitly perform any other required cleanup at the appropriate point in time. • Other kinds of cleanup could involve closing files, disconnecting from open telephone lines, etc. Object Oriented Programming in Java (95-707)Java Language Basics
Garbage Collection • The sole purpose of garbage collection is to reclaim memory occupied by objects that are no longer needed. • Eligibility for garbage collection • An object becomes eligible for garbage collection when there are no more references to that object. You can make an object eligible for garbage collection by setting all references to that object to null, or allowing them to go out of scope. Object Oriented Programming in Java (95-707)Java Language Basics
No Guarantees • However, just because an object is eligible for garbage collection doesn't mean that it will be reclaimed. • The garbage collector runs in a low-priority thread, and presumably is designed to create minimal interference with the other threads of the program. Therefore, the garbage collector may not run unless a memory shortage is detected. And when it does run, it runs asynchronously relative to the other threads in the program. Object Oriented Programming in Java (95-707)Java Language Basics
Finalize Method • Before the garbage collector reclaims the memory occupied by an object, it calls the object's finalize() method. • The finalize() method is a member of the Object class. Since all classes inherit from the Object class, your classes also contain the default finalize() method. This gives you an opportunity to execute your special cleanup code on each object before the memory is reclaimed • In order to make use of the finalize()method, you must override it, providing the code that you want to have executed before the memory is reclaimed. (We will discuss overriding methods in detail later.) Object Oriented Programming in Java (95-707)Java Language Basics
When do I use the finalize() method • Is the cleanup timing critical? • If you simply need to do cleanup work on an object sometime before the program terminates, (and you have specified finalization on exit) you can ALMOST depend on your overridden finalize() method being executed sometime before the program terminates. • If you need cleanup work to be performed earlier (such as disconnecting an open long-distance telephone call), you must explicitly call methods to do cleanup at the appropriate point in time and not depend on finalization to get the job done. • If you use the finalize() method, make sure that you call the super.finalize() method at the end of it. Object Oriented Programming in Java (95-707)Java Language Basics
Examples with finalize() Object Oriented Programming in Java (95-707)Java Language Basics
Arrays • Data structure that holds multiple values of the same type. • The length of the array is set during creation of the array. It cannot change afterwards. • You can access each element of the array by an index • The index starts at 0 (zero) Object Oriented Programming in Java (95-707)Java Language Basics
Declaring and Creating Arrays • Declaring • int[] arrayOfInts; • String[] arrayOfStrings; • AnyObject[] arrayOfAnyObjects; • remember declaring does not allocate any memory! • Creation (instantiation) • arrayOfInts = new int[10]; • arrayOfStrings = new String[20]; • arrayOfAnyObjects = new AnyObject[30]; Object Oriented Programming in Java (95-707)Java Language Basics
Accessing Arrays • Size of the array can be obtained with: • arrayVariableName.length • note that this is not “length()” with parenthesis • You access each element with its index: • arrayVariableName[0] • arrayVariableName[1] • arrayVariableName[...] • Examples: • int I = arrayOfInts[9]; • String s = arrayOfStrings[0] • AnyObject ao = arrayOfAnyObjects[4]; Object Oriented Programming in Java (95-707)Java Language Basics
Loops and Arrays - I • Loops are often used to iterate through an array • Let’s initialize “arrayOfInts” that we saw earlier: int[] arrayOfInts; arrayOfInts = new int[10]; for (int i = o; i<arryOfInts.length; i++){ arrayOfInts[i] = i+1; } Object Oriented Programming in Java (95-707)Java Language Basics
Loops and Arrays - II • Let’s read the array “arrayOfInts” that we saw earlier: int[] arrayOfInts; arrayOfInts = new int[10]; for (int i = o; i<arryOfInts.length; i++){ arrayOfInts[i] = i+1; } for (int i = o; i<arryOfInts.length; i++){ System.out.println( “At i = “ + i “ >>> “ + arrayOfInts[i]); } Object Oriented Programming in Java (95-707)Java Language Basics
Who populates the array? • Declaring and creating does NOT mean populating • “Declaring” is like making the plans for a house • “Creating” is like building the house • Yet, no one is there until a family moves in • The following will cause a runtime exception: int[] arrayOfStrings; arrayOfStrings = new String[10]; for (int i = o; i<arrayOfStrings.length; i++){ System.out.println(arrayOfStrings[i].toLowerCase()); } Object Oriented Programming in Java (95-707)Java Language Basics
Shortcuts • int[] arrayOfInts = {1,2,3,4,5,6,7,8,9,10}; • String[] arrayOfStrings = {“Alain”,”Kouyate”}; Object Oriented Programming in Java (95-707)Java Language Basics
Revisiting Interfaces Object Oriented Programming in Java (95-707)Java Language Basics
Why do we need interfaces? • An interface is a collection of method definitions (without implementations) • You use interfaces to define a protocol of behavior that can be implemented by any class anywhere in the class hierarchy. • Interfaces are useful for: • capturing similarities between unrelated classes without forcing a class relationship • declaring methods that one or more classes are expected to implement • revealing an object's programming interface without revealing its class (objects such as these are called anonymous objects and can be useful when shipping a package of classes to other developers) Object Oriented Programming in Java (95-707)Java Language Basics
Interfaces and Inheritance • Often interfaces are touted as an alternative to multiple class inheritance. While interfaces may solve some of the same problems as multiple class inheritance, they are quite different animals. In particular: • you cannot inherit variables from an interface • you cannot inherit method implementations from an interface. • the interface hierarchy is independent of the class hierarchy--classes that implement the same interface may or may not be related through the class hierarchy. Object Oriented Programming in Java (95-707)Java Language Basics
Bottom Line on Interfaces • The interface makes it possible for a method in one class to invoke methods on objects of other classes, without the requirement to know the true class of those objects, provided that those objects are instantiated from classes that implement one or more specified interfaces. • In other words, objects of classes that implement specified interfaces can be passed into the methods of other objects as the generic type Object, and the methods of the other object can invoke methods on the incoming objects by first casting them as the interface type. • This provides a significant degree of generality in your programming capability Object Oriented Programming in Java (95-707)Java Language Basics
Design Strategy Tip • Question: How do you make member variables read-only after they have been initialized? • Answer: there are two strategies: • working with the accessors of the variable • working with the final keyword Object Oriented Programming in Java (95-707)Java Language Basics