umass lowell computer science 91.460 java and distributed computing prof. karen daniels fall, 2000

52
UMass Lowell Computer Science 91.460 Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 12 Lecture 12 Java Fundamentals Java Fundamentals Exception Handling Exception Handling Objects/Classes:Polymorphism Objects/Classes:Polymorphism Backup Material Backup Material Mon. 10/2/00 Mon. 10/2/00

Upload: hera

Post on 12-Jan-2016

22 views

Category:

Documents


0 download

DESCRIPTION

UMass Lowell Computer Science 91.460 Java and Distributed Computing Prof. Karen Daniels Fall, 2000. Lecture 12 Java Fundamentals Exception Handling Objects/Classes:Polymorphism Backup Material Mon. 10/2/00. Homework #3. HW# Assigned Due Content. - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: UMass Lowell Computer Science 91.460 Java and Distributed Computing Prof. Karen Daniels Fall, 2000

UMass Lowell Computer Science 91.460

Java and Distributed Computing

Prof. Karen Daniels Fall, 2000

UMass Lowell Computer Science 91.460

Java and Distributed Computing

Prof. Karen Daniels Fall, 2000

Lecture 12Lecture 12Java FundamentalsJava Fundamentals

Exception HandlingException HandlingObjects/Classes:PolymorphismObjects/Classes:Polymorphism

Backup MaterialBackup Material

Mon. 10/2/00Mon. 10/2/00

Page 2: UMass Lowell Computer Science 91.460 Java and Distributed Computing Prof. Karen Daniels Fall, 2000

Homework #3Homework #3

11 Fri, 9/8 Fri, 9/15 Fri, 9/8 Fri, 9/15 Part 1Part 1

Mon, 9/18 Mon, 9/18 Part 2Part 2

22 Fri, 9/15 Fri, 9/22 Fri, 9/15 Fri, 9/22 Part 1 & Part 2Part 1 & Part 2

33 Fri, 9/22Fri, 9/22 Fri, 9/29 Fri, 9/29 Part 1 & Part 2Part 1 & Part 2

HW#HW# AssignedAssigned DueDue ContentContent

Homework is due at the start of lecture on the due date.Homework is due at the start of lecture on the due date.

Homework #4 will be assigned on Fri., 10/6Homework #4 will be assigned on Fri., 10/6

(skipping one week due to test)(skipping one week due to test)

Page 3: UMass Lowell Computer Science 91.460 Java and Distributed Computing Prof. Karen Daniels Fall, 2000

Exam 1Exam 1

Topics not coveredTopics not covered: Exception Handling & Files/Streams: Exception Handling & Files/Streams

FormatFormat: Multiple choice: Multiple choice

Page 4: UMass Lowell Computer Science 91.460 Java and Distributed Computing Prof. Karen Daniels Fall, 2000

Java Fundamentals Java Fundamentals

Exception HandlingException Handling((much of this material is frommuch of this material is from

Java2: The Complete Reference)Java2: The Complete Reference)

Page 5: UMass Lowell Computer Science 91.460 Java and Distributed Computing Prof. Karen Daniels Fall, 2000

Exception HandlingException Handling

Exception: Exception: Is a Is a Run-TimeRun-Time Error :“abnormal condition that arises Error :“abnormal condition that arises

in a code sequence at run time”in a code sequence at run time” Java treats exceptions in Object-Oriented wayJava treats exceptions in Object-Oriented way

Exception is an object describing an error conditionException is an object describing an error condition When error condition occurs, exception object is When error condition occurs, exception object is

created and created and thrownthrown in method where error occurs in method where error occurs Method may:Method may:

catchcatch the exception and handle it the exception and handle it pass it on: pass it on: throwthrow it up to invoking method it up to invoking method

Java Exception Handling Keywords: Java Exception Handling Keywords: trytry, , catchcatch, , throwthrow, , throwsthrows,, finally finally

Remember Remember trytry, , catchcatch, , throwthrow, exception handling from C++?, exception handling from C++?

Page 6: UMass Lowell Computer Science 91.460 Java and Distributed Computing Prof. Karen Daniels Fall, 2000

Exception HandlingException Handling

try{try{ // Block of code that may generate errors// Block of code that may generate errors}}catch ( catch ( ExceptionType1ExceptionType1 exOb ) { exOb ) { // Exception handler for // Exception handler for ExceptionType1ExceptionType1}}catch (catch (ExceptionType2ExceptionType2 exOb ) { exOb ) { // Exception handler for // Exception handler for ExceptionType2ExceptionType2}}//...//...

finally{finally{ // Block of code to be executed before try block ends// Block of code to be executed before try block ends}}

Page 7: UMass Lowell Computer Science 91.460 Java and Distributed Computing Prof. Karen Daniels Fall, 2000

Exception Handling:Class Casting & Null Pointer ExampleException Handling:Class Casting & Null Pointer Example

public class PolyTest {public class PolyTest {public static void main(String args[]) {public static void main(String args[]) { B b = new B();B b = new B(); Object c = new Object();Object c = new Object(); polyInit(b);polyInit(b); polyInit(c);polyInit(c);}}public static void polyInit(Object q){ // (Could use parameter variable of type A)public static void polyInit(Object q){ // (Could use parameter variable of type A) A a = null;A a = null; try{ // (Alternatively,could use instanceof to test if q is of type A -- see later slide)try{ // (Alternatively,could use instanceof to test if q is of type A -- see later slide) a = (A)q; }a = (A)q; } catch(ClassCastException ccex) {catch(ClassCastException ccex) { System.out.println("Class cast exception in casting q to a in polyInit()");}System.out.println("Class cast exception in casting q to a in polyInit()");} try{ a.foo(); } try{ a.foo(); } catch(NullPointerException npex) { catch(NullPointerException npex) { System.out.println("Null pointer exception in polyInit()");}System.out.println("Null pointer exception in polyInit()");} }}}}class A { public void foo() { System.out.println("A's foo"); } }class A { public void foo() { System.out.println("A's foo"); } }class B extends A { public void foo() { System.out.println("B's foo"); } }class B extends A { public void foo() { System.out.println("B's foo"); } }

This is a contrived example. Output:

B’s foo Class cast exception in casting q to a in polyInit()Null pointer exception in polyInit()

Page 8: UMass Lowell Computer Science 91.460 Java and Distributed Computing Prof. Karen Daniels Fall, 2000

Exception Handling:Class Casting & Null Pointer ExampleException Handling:Class Casting & Null Pointer Example

public class PolyTest {public class PolyTest {public static void main(String args[]) {public static void main(String args[]) { B b = new B();B b = new B(); Object c = new Object();Object c = new Object(); polyInit(b);polyInit(b); polyInit(c);polyInit(c);}}public static void polyInit(Object q){ public static void polyInit(Object q){ A a = null;A a = null; try{ a = (A)q;try{ a = (A)q; a.foo(); }a.foo(); } catch(ClassCastException ccex) {catch(ClassCastException ccex) { System.out.println("Class cast exception in casting q to a in polyInit()");}System.out.println("Class cast exception in casting q to a in polyInit()");} catch(NullPointerException npex) { catch(NullPointerException npex) { System.out.println("Null pointer exception in polyInit()");}System.out.println("Null pointer exception in polyInit()");} }}}}class A { public void foo() { System.out.println("A's foo"); } }class A { public void foo() { System.out.println("A's foo"); } }class B extends A { public void foo() { System.out.println("B's foo"); } }class B extends A { public void foo() { System.out.println("B's foo"); } }

Multiple catch clausesMultiple catch clauses

Multiple statements in try blockMultiple statements in try block

Page 9: UMass Lowell Computer Science 91.460 Java and Distributed Computing Prof. Karen Daniels Fall, 2000

Exception Handling:Class Casting & Null Pointer ExampleException Handling:Class Casting & Null Pointer Example

public class PolyTest2 {public class PolyTest2 {public static void main(String args[]) {public static void main(String args[]) { B b = new B();B b = new B(); B d = null;B d = null; Object c = new Object();Object c = new Object(); try{ polyInit(b);try{ polyInit(b); polyInit(c); }polyInit(c); } catch (ClassCastException ccex) {catch (ClassCastException ccex) { System.out.println("main(): Class cast exception in casting q to a in polyInit()");}System.out.println("main(): Class cast exception in casting q to a in polyInit()");} polyInit(d);polyInit(d);}}public static void polyInit(Object q) public static void polyInit(Object q)

throws ClassCastException, NullPointerException{ throws ClassCastException, NullPointerException{ A a = null;A a = null; try{ a = (A)q;try{ a = (A)q; a.foo(); }a.foo(); } catch(ClassCastException ccex) {catch(ClassCastException ccex) { System.out.println("Class cast exception in casting q to a in polyInit()");System.out.println("Class cast exception in casting q to a in polyInit()"); throw ccex; }throw ccex; } }}}}class A { public void foo() { System.out.println("A's foo"); } }class A { public void foo() { System.out.println("A's foo"); } }class B extends A { public void foo() { System.out.println("B's foo"); } }class B extends A { public void foo() { System.out.println("B's foo"); } }

Throw ClassCastExceptionThrow ClassCastException

Throw exceptions up one levelThrow exceptions up one level

NullPointerException is not caughtNullPointerException is not caught

Output:B’s foo Class cast exception in casting q to a in polyInit()main(): Class cast exception in casting q to a in polyInit()Exception in thread “main” java.lang.NullPointerException: at PolyTest2.polyInit(PolyTest2.java:17) at PolyTest2.main(PolyTest2.java:11)

Catch exception againCatch exception again

Page 10: UMass Lowell Computer Science 91.460 Java and Distributed Computing Prof. Karen Daniels Fall, 2000

Exception Handling:File I/O ExampleException Handling:File I/O Example

try{ try{ output.close( );output.close( ); } } catch (IOException ioex) { catch (IOException ioex) { JOptionPane.showMessageDialog(null, “Error closing file”, JOptionPane.showMessageDialog(null, “Error closing file”,

“Error”, JOptionPane.ERROR_MESSAGE); “Error”, JOptionPane.ERROR_MESSAGE); }}

Page 11: UMass Lowell Computer Science 91.460 Java and Distributed Computing Prof. Karen Daniels Fall, 2000

Exception Handling: Some Built-in ExceptionsException Handling: Some Built-in Exceptions

ArithmeticExceptionArithmeticException ArrayIndexOutOfBoundsExceptionArrayIndexOutOfBoundsException NullPointerExceptionNullPointerException ClassCastExceptionClassCastException ClassNotFoundExceptionClassNotFoundException SecurityExceptionSecurityException InterruptedExceptionInterruptedException IOExceptionIOException

ExceptionException MeaningMeaning

Arithmetic error (e.g. Divide-Arithmetic error (e.g. Divide-by-0)by-0)

Array index out of boundsArray index out of bounds Invalid use of null referenceInvalid use of null reference Invalid castInvalid cast Class not foundClass not found Attempt to violate securityAttempt to violate security A thread has been interrupted A thread has been interrupted

by another threadby another thread Problem with a file I/O Problem with a file I/O

operationoperation

Page 12: UMass Lowell Computer Science 91.460 Java and Distributed Computing Prof. Karen Daniels Fall, 2000

Java Fundamentals Java Fundamentals

Objects/Classes: PolymorphismObjects/Classes: Polymorphism

Page 13: UMass Lowell Computer Science 91.460 Java and Distributed Computing Prof. Karen Daniels Fall, 2000

A Motivation...Polymorphic GraphicsA Motivation...Polymorphic Graphics

Static Resource ArrayStatic Resource Array

withinwithin

Resource ClassResource Class

Page 14: UMass Lowell Computer Science 91.460 Java and Distributed Computing Prof. Karen Daniels Fall, 2000

“Casting” between Objects“Casting” between Objects

Explicit reference casts between types related by inheritance:Explicit reference casts between types related by inheritance: If class A is extended by class B, and myA is a reference to an A and If class A is extended by class B, and myA is a reference to an A and

myB is a reference to a B:myB is a reference to a B: myA = (A) myB, and myB = (B) myA are valid castsmyA = (A) myB, and myB = (B) myA are valid casts Don’t Don’t need toneed to (but can) cast from a subclass to a superclass reference (but can) cast from a subclass to a superclass reference

(e.g., myA = myB does not need the explicit cast)(e.g., myA = myB does not need the explicit cast)

Casting from a supertype reference to a subtype reference is Casting from a supertype reference to a subtype reference is potentially dangerouspotentially dangerous If the supertype reference is not actually referring to an instance of the If the supertype reference is not actually referring to an instance of the

specified subclass, a runtime exception will be thrownspecified subclass, a runtime exception will be thrown This can be avoided by doing an This can be avoided by doing an instanceofinstanceof test prior to the cast test prior to the cast

if (myA instanceof B) { myB = (B) myA; }if (myA instanceof B) { myB = (B) myA; }

AA

BB

Casting from subtype reference to supertype reference does Casting from subtype reference to supertype reference does not remove subtype members, just “hide” themnot remove subtype members, just “hide” them

Page 15: UMass Lowell Computer Science 91.460 Java and Distributed Computing Prof. Karen Daniels Fall, 2000

PolymorphismPolymorphism

Allows for the specific behavior of certain Allows for the specific behavior of certain method invocations to be determined at run-method invocations to be determined at run-time based on the specific subclass to which it time based on the specific subclass to which it belongsbelongs Does not require compile-time knowledge of types Does not require compile-time knowledge of types

(at the point of use)(at the point of use) Used with inheritanceUsed with inheritance

Subclass instances are accessed via superclass Subclass instances are accessed via superclass referencesreferences

Page 16: UMass Lowell Computer Science 91.460 Java and Distributed Computing Prof. Karen Daniels Fall, 2000

PolymorphismPolymorphism

Allows instances of different classes to be Allows instances of different classes to be treated as if they were instances of the same treated as if they were instances of the same (super) class(super) class Can, for example, perform the same operation on Can, for example, perform the same operation on

each object in a list of different types of objectseach object in a list of different types of objects Specific action depends on the specific type of the Specific action depends on the specific type of the

object at run-timeobject at run-time Greatly enhances the extensibility of a programGreatly enhances the extensibility of a program

Can add derived classes very easilyCan add derived classes very easily

Page 17: UMass Lowell Computer Science 91.460 Java and Distributed Computing Prof. Karen Daniels Fall, 2000

Realizing PolymorphismRealizing Polymorphism

Superclass declares (and possibly defines) a methodSuperclass declares (and possibly defines) a method One or more subclasses override the superclass methodOne or more subclasses override the superclass method A superclass reference is used at the point of invocationA superclass reference is used at the point of invocation

The actual instance referred to might be a subclass instanceThe actual instance referred to might be a subclass instance At run-time, depending on the actual type of the At run-time, depending on the actual type of the

instance, the appropriate method is executedinstance, the appropriate method is executed

Page 18: UMass Lowell Computer Science 91.460 Java and Distributed Computing Prof. Karen Daniels Fall, 2000

Polymorphism ExamplePolymorphism Example

AutomobileAutomobilemaxSpeed: intmaxSpeed: int

GetMaxSpeed( )GetMaxSpeed( )

ObjectObject

LexusLexusmaxSpeed: static intmaxSpeed: static int

GetMaxSpeed( )GetMaxSpeed( )foo( )foo( )

YugoYugomaxSpeed: intmaxSpeed: int

GetMaxSpeed( )GetMaxSpeed( )foo( )foo( )

Inheritance tree using Unified Modeling Language (UML) Inheritance tree using Unified Modeling Language (UML)

different from different from automobileautomobile

Page 19: UMass Lowell Computer Science 91.460 Java and Distributed Computing Prof. Karen Daniels Fall, 2000

Polymorphism ExamplePolymorphism Example

public class Automobile extends Object {public class Automobile extends Object {

int maxSpeed = 55; // can be staticint maxSpeed = 55; // can be static

public int GetMaxSpeed() { return maxSpeed; } public int GetMaxSpeed() { return maxSpeed; }

// cannot be static// cannot be static

// need not be abstract// need not be abstract

public static void main(String args[ ])public static void main(String args[ ])

{{

// see later slide// see later slide

}}

}}

Page 20: UMass Lowell Computer Science 91.460 Java and Distributed Computing Prof. Karen Daniels Fall, 2000

Polymorphism ExamplePolymorphism Example

class Lexus extends Automobile {class Lexus extends Automobile {

static int maxSpeed = 85; // can be non-staticstatic int maxSpeed = 85; // can be non-static

public int GetMaxSpeed() { return maxSpeed; } // must not be staticpublic int GetMaxSpeed() { return maxSpeed; } // must not be static

public void foo() { System.out.println("In Lexus foo()"); }public void foo() { System.out.println("In Lexus foo()"); }

}}

class Yugo extends Automobile {class Yugo extends Automobile {

int maxSpeed = 35; // can be staticint maxSpeed = 35; // can be static

public int GetMaxSpeed() { return maxSpeed; } // must not be staticpublic int GetMaxSpeed() { return maxSpeed; } // must not be static

public void foo() {System.out.println("In Yugo foo()"); }public void foo() {System.out.println("In Yugo foo()"); }

}}

Page 21: UMass Lowell Computer Science 91.460 Java and Distributed Computing Prof. Karen Daniels Fall, 2000

Polymorphism ExamplePolymorphism Example

LexusLexus YugoYugo

Automobile A1 = new Lexus();Automobile A1 = new Lexus(); Automobile A2 = new Yugo();Automobile A2 = new Yugo();

A1A1 A2A2

LexusLexusImplementationImplementation

YugoYugoImplementationImplementation Non-static behavior Non-static behavior

decided at runtimedecided at runtime

Page 22: UMass Lowell Computer Science 91.460 Java and Distributed Computing Prof. Karen Daniels Fall, 2000

Polymorphism ExamplePolymorphism Example

public static void main(String args[ ]) // for class Automobilepublic static void main(String args[ ]) // for class Automobile {{ Automobile myAutos[ ] = new Automobile[3];Automobile myAutos[ ] = new Automobile[3]; myAutos[0] = new Automobile();myAutos[0] = new Automobile(); myAutos[1] = new Lexus(); // see next slidemyAutos[1] = new Lexus(); // see next slide myAutos[2] = new Yugo(); // see next slidemyAutos[2] = new Yugo(); // see next slide for (int i = 0; i < myAutos.length; i++)for (int i = 0; i < myAutos.length; i++) {{ System.out.println("Max Speed ="+ myAutos[i].GetMaxSpeed());System.out.println("Max Speed ="+ myAutos[i].GetMaxSpeed());

//myAutos[i].foo(); // Will generate compiler error//myAutos[i].foo(); // Will generate compiler error // Because automobile does not have a foo method!// Because automobile does not have a foo method! if (myAutos[i] instanceof Lexus) ((Lexus) myAutos[i]).foo();if (myAutos[i] instanceof Lexus) ((Lexus) myAutos[i]).foo(); if (myAutos[i] instanceof Yugo) ((Yugo) myAutos[i]).foo();if (myAutos[i] instanceof Yugo) ((Yugo) myAutos[i]).foo(); }}}}

Output:Output:Max Speed = 55Max Speed = 55Max Speed = 85Max Speed = 85Max Speed = 35Max Speed = 35

Page 23: UMass Lowell Computer Science 91.460 Java and Distributed Computing Prof. Karen Daniels Fall, 2000

Polymorphism vs a switchPolymorphism vs a switch

A A switchswitch is a multiple-select control structure is a multiple-select control structure Execute a behavior based on a conditionExecute a behavior based on a condition

The problem with switches (and nested if's) is that you The problem with switches (and nested if's) is that you have to know AT COMPILE TIME all of the selection have to know AT COMPILE TIME all of the selection conditionsconditions and subsequent and subsequent behaviorbehavior AT THE AT THE LOCATION of the multiple selectionLOCATION of the multiple selection

Polymorphism presents a multiple select behavior in Polymorphism presents a multiple select behavior in which you don't need to know at compile time either which you don't need to know at compile time either the specific selection conditions (i.e., the class type) or the specific selection conditions (i.e., the class type) or the subsequent behaviorthe subsequent behavior

Page 24: UMass Lowell Computer Science 91.460 Java and Distributed Computing Prof. Karen Daniels Fall, 2000

Java Fundamentals Java Fundamentals

Objects/Classes: Backup MaterialObjects/Classes: Backup Material

Page 25: UMass Lowell Computer Science 91.460 Java and Distributed Computing Prof. Karen Daniels Fall, 2000

Backup TopicsBackup Topics

class Objectclass Object garbage collectiongarbage collection operator operator newnew command line argumentscommand line arguments packagepackagess adding stringsadding strings

thisthis keyword and this() keyword and this() constructors and super()constructors and super() finalizers (destructors)finalizers (destructors) nested (inner) classesnested (inner) classes abstractabstract classes classes interfacesinterfaces

Page 26: UMass Lowell Computer Science 91.460 Java and Distributed Computing Prof. Karen Daniels Fall, 2000

Referencing thisReferencing this

‘‘this’ is an explicit reference to the instance of a class this’ is an explicit reference to the instance of a class on which a (non-static) method is invoked for use on which a (non-static) method is invoked for use within that methodwithin that method Can think of a (non-static) method as having an implicit Can think of a (non-static) method as having an implicit

first argument ("this")first argument ("this") Can be used to solve naming conflicts between Can be used to solve naming conflicts between

parameters and instance variablesparameters and instance variables E.g., this.name = nameE.g., this.name = name

Static methods have no "this" referenceStatic methods have no "this" reference They are not (always) invoked on an instanceThey are not (always) invoked on an instance

Page 27: UMass Lowell Computer Science 91.460 Java and Distributed Computing Prof. Karen Daniels Fall, 2000

Example of using thisExample of using this

public class MyClasspublic class MyClass{{

private final static int MAX_NUM_INSTANCES = 100;private final static int MAX_NUM_INSTANCES = 100;private static MyClass myClassInstances[];private static MyClass myClassInstances[];private static int numInstances;private static int numInstances;

static { myClassInstances = new MyClass[MAX_NUM_INSTANCES ]; static { myClassInstances = new MyClass[MAX_NUM_INSTANCES ]; numInstances = 0; }numInstances = 0; }......public MyClass() { /* do stuff as desired */ RememberInstance(this); }public MyClass() { /* do stuff as desired */ RememberInstance(this); }

private void RememberInstance(MyClass myClassRef)private void RememberInstance(MyClass myClassRef){{

if (numInstances < MAX_NUM_INSTANCES )if (numInstances < MAX_NUM_INSTANCES ){{

myClassInstances[numInstances++] = myClassRef;myClassInstances[numInstances++] = myClassRef;}}

}}......

}}

Page 28: UMass Lowell Computer Science 91.460 Java and Distributed Computing Prof. Karen Daniels Fall, 2000

Constructors and super( )Constructors and super( )

Constructors are not inheritedConstructors are not inherited Default (null) superclass constructor is Default (null) superclass constructor is

called implicitly before all subclass called implicitly before all subclass constructorsconstructors (and their superclass null constructors in turn)(and their superclass null constructors in turn)

Superclass constructors can be called Superclass constructors can be called explicitly using the explicitly using the supersuper keyword keyword Must be the first executable statement in the Must be the first executable statement in the

subclass constructorsubclass constructor

Page 29: UMass Lowell Computer Science 91.460 Java and Distributed Computing Prof. Karen Daniels Fall, 2000

this() and super()this() and super()

Provide mechanisms to explicitly invoke a Provide mechanisms to explicitly invoke a constructor from within another constructor of constructor from within another constructor of the same class (the same class (thisthis()) or a subclass (()) or a subclass (supersuper())())

If present, either If present, either supersuper() or () or thisthis() must be the () must be the first call in a constructor (only one can be first call in a constructor (only one can be present)present)

Must contain an appropriate list of arguments to Must contain an appropriate list of arguments to match a corresponding constructor in the match a corresponding constructor in the appropriate classappropriate class

Page 30: UMass Lowell Computer Science 91.460 Java and Distributed Computing Prof. Karen Daniels Fall, 2000

Example of this() and super()Example of this() and super()

public class Boxpublic class Box{{

private double top, left, bottom, right;private double top, left, bottom, right;public Box(Point top_left, double bottom, public Box(Point top_left, double bottom,

double right)double right){{

top = top_left.y();top = top_left.y();left = top_left.x();left = top_left.x();this.bottom = bottom;this.bottom = bottom;this.right = right;this.right = right;

}}public Box(double x, double y, public Box(double x, double y,

double width, double height)double width, double height){{

this(Point(x, y), this(Point(x, y), right-left, bottom-top);right-left, bottom-top);

}}}}

public class MyBox extends Boxpublic class MyBox extends Box{{

private int boxColor;private int boxColor;public MyBox(double x, double y, public MyBox(double x, double y,

double width, double height, double width, double height, int color)int color)

{{super(x, y, width, height);super(x, y, width, height);boxColor = color;boxColor = color;

}}}}

Page 31: UMass Lowell Computer Science 91.460 Java and Distributed Computing Prof. Karen Daniels Fall, 2000

Finalizers (Destructors)Finalizers (Destructors)

Class Object defines a finalizerClass Object defines a finalizer void finalize();void finalize(); Gets invoked by garbage collectorGets invoked by garbage collector

Programmer-defined classes can override finalizeProgrammer-defined classes can override finalize Used to “clean up”Used to “clean up”

For example, release (non-memory) system resources For example, release (non-memory) system resources (such as bitmaps, graphics media)(such as bitmaps, graphics media)

Not as important as in C or C++Not as important as in C or C++

Page 32: UMass Lowell Computer Science 91.460 Java and Distributed Computing Prof. Karen Daniels Fall, 2000

Finalizers (Destructors) Finalizers (Destructors)

Question: If an object is no longer referenced, Question: If an object is no longer referenced, but it references some other object, does Java but it references some other object, does Java automatically clean up that reference when the automatically clean up that reference when the object is garbage collected?object is garbage collected?

This referenceThis referenceis removedis removed Is this one?Is this one?

Page 33: UMass Lowell Computer Science 91.460 Java and Distributed Computing Prof. Karen Daniels Fall, 2000

Finalizers (Destructors)Finalizers (Destructors)

If you define a finalize method for your class, it:If you define a finalize method for your class, it: Should be declared protectedShould be declared protected Should be the only oneShould be the only one Should invoke the superclass finalizer as its last step Should invoke the superclass finalizer as its last step

(i.e., (i.e., supersuper.finalize()).finalize()) Can be explicitly invoked (like any other Can be explicitly invoked (like any other

method)method) Does not initiate garbage collectionDoes not initiate garbage collection An object can be “saved” in a finalizer by An object can be “saved” in a finalizer by

creating a reference to itcreating a reference to it

Page 34: UMass Lowell Computer Science 91.460 Java and Distributed Computing Prof. Karen Daniels Fall, 2000

Finalizer (Destructor) ExamplesFinalizer (Destructor) Examples

public class MyClasspublic class MyClass

{{

private final static int MAX_NUM_INSTANCES = 100;private final static int MAX_NUM_INSTANCES = 100;

private static MyClass myClassInstances[];private static MyClass myClassInstances[];

private static int numInstances;private static int numInstances;

static { myClassInstances = new MyClass[MAX_NUM_INSTANCES ]; numInstances = 0; }static { myClassInstances = new MyClass[MAX_NUM_INSTANCES ]; numInstances = 0; }

......

public MyClass() { /* do stuff as desired */ RememberInstance(this); }public MyClass() { /* do stuff as desired */ RememberInstance(this); }

protected void finalize()protected void finalize()

{{

// decrement numInstances, delete ref from myClassInstances (to include // decrement numInstances, delete ref from myClassInstances (to include compacting the array)compacting the array)

}}

......

}}

Page 35: UMass Lowell Computer Science 91.460 Java and Distributed Computing Prof. Karen Daniels Fall, 2000

Nested ClassesNested Classes

Nested class = class within a classNested class = class within a class Scope of nested class is bounded by scope of Scope of nested class is bounded by scope of

enclosing classenclosing class Nested class has access to members (even private) Nested class has access to members (even private)

of enclosing classof enclosing class Enclosing class does not have access to members of Enclosing class does not have access to members of

nested classnested class Static nested class: not often usedStatic nested class: not often used Inner class (non-static): used often for GUIs to Inner class (non-static): used often for GUIs to

handle eventshandle events We’ll use these for GUIs and also for JiniWe’ll use these for GUIs and also for Jini

Page 36: UMass Lowell Computer Science 91.460 Java and Distributed Computing Prof. Karen Daniels Fall, 2000

Inheritance vs NestingInheritance vs Nesting

Scope:Scope: A non-static nested class is known only within A non-static nested class is known only within

scope of enclosing classscope of enclosing class A subclass can be known outside its superclassA subclass can be known outside its superclass

Access:Access: A nested class can access members (even A nested class can access members (even

private ones) of enclosing classprivate ones) of enclosing class A subclass cannot directly access private A subclass cannot directly access private

members of its superclassmembers of its superclass

Page 37: UMass Lowell Computer Science 91.460 Java and Distributed Computing Prof. Karen Daniels Fall, 2000

abstract Classesabstract Classes

An An abstractabstract class is designed to be a class is designed to be a superclass onlysuperclass only Not designed to have any instances (no objects Not designed to have any instances (no objects

of the generic type represented by that class)of the generic type represented by that class) Example: class Resource vs class Airport and Example: class Resource vs class Airport and

class Planeclass Plane Syntax: Syntax: abstractabstract class className { // class className { //

classBody }classBody }

Page 38: UMass Lowell Computer Science 91.460 Java and Distributed Computing Prof. Karen Daniels Fall, 2000

abstract Classesabstract Classes

An abstract class can have certain state and behavior that An abstract class can have certain state and behavior that is common to subclassesis common to subclasses Otherwise, we would use an Otherwise, we would use an interfaceinterface

If a class extends an abstract class and does not define an If a class extends an abstract class and does not define an abstract method in that abstract class, it is also abstractabstract method in that abstract class, it is also abstract

An abstract class can have non-abstract methods and An abstract class can have non-abstract methods and instance variablesinstance variables

A class with abstract methods must be declared abstractA class with abstract methods must be declared abstract [A concrete class is one that can have instances][A concrete class is one that can have instances]

Page 39: UMass Lowell Computer Science 91.460 Java and Distributed Computing Prof. Karen Daniels Fall, 2000

abstract Class Exampleabstract Class Example

abstract class Resourceabstract class Resource

{{

private Point2D location;private Point2D location;

private String name;private String name;

protected Resource(Point2D pt, String name) { /* do stuff as desired */ }protected Resource(Point2D pt, String name) { /* do stuff as desired */ }

abstract public void Draw(Graphics gc);abstract public void Draw(Graphics gc);

}}

public class Airplane extends Resourcepublic class Airplane extends Resource

{{

private boolean loadedStatus;private boolean loadedStatus;

public Airplane(Point2D pt, String name) { super(pt, name); loadedStatus public Airplane(Point2D pt, String name) { super(pt, name); loadedStatus = false; }= false; }

public void Draw(Graphics gc) { // do stuff, possibly with loadedStatus }public void Draw(Graphics gc) { // do stuff, possibly with loadedStatus }

}}

Page 40: UMass Lowell Computer Science 91.460 Java and Distributed Computing Prof. Karen Daniels Fall, 2000

interfacesinterfaces

An An interfaceinterface defines a collection of methods (is a defines a collection of methods (is a collection of method signatures)collection of method signatures)

A class A class implementsimplements an interface an interface An interface can also define constants (An interface can also define constants (final staticfinal static data) data) Interfaces are Interfaces are abstract abstract (all their method declarations are (all their method declarations are

publicpublic abstractabstract)) Interfaces can be imported (like classes)Interfaces can be imported (like classes) Syntax: modifiers interface InterfaceName Syntax: modifiers interface InterfaceName

extendsClause { // interface body }extendsClause { // interface body }

Page 41: UMass Lowell Computer Science 91.460 Java and Distributed Computing Prof. Karen Daniels Fall, 2000

interfaces (concluded)interfaces (concluded)

A class can implement one or moreA class can implement one or more interface interfaces (sets of s (sets of method specs)method specs) Must implement every method in the Must implement every method in the interfaceinterface Else, becomes an Else, becomes an abstractabstract class class

Used in place of an Used in place of an abstractabstract class that does not provide class that does not provide any implementationany implementation

Are normally defined in files of their own (just like Are normally defined in files of their own (just like publicpublic classes) classes)

Presents an “is-a” relationship like inheritancePresents an “is-a” relationship like inheritance Can be used to define related constants (like including Can be used to define related constants (like including

a “constants.h” file in C/C++)a “constants.h” file in C/C++)

Page 42: UMass Lowell Computer Science 91.460 Java and Distributed Computing Prof. Karen Daniels Fall, 2000

class Objectclass Object

Parent class for all Java classesParent class for all Java classes Every class inherits the methods and data Every class inherits the methods and data

members of class Objectmembers of class Object For example, String Object.toString() – convert For example, String Object.toString() – convert

an instance of a derived class to a Stringan instance of a derived class to a String Normally redefined by each classNormally redefined by each class Called by automatic conversion (e.g., concatenation Called by automatic conversion (e.g., concatenation

of a string with an object)of a string with an object)

Page 43: UMass Lowell Computer Science 91.460 Java and Distributed Computing Prof. Karen Daniels Fall, 2000

Garbage CollectionGarbage Collection

When an object has no more references, it is When an object has no more references, it is marked for collectionmarked for collection

Applies to both applications and appletsApplies to both applications and applets System.gc – suggest that the system do System.gc – suggest that the system do

garbage collectiongarbage collection Runs as a separate threadRuns as a separate thread No telling when it might do its thingNo telling when it might do its thing

Page 44: UMass Lowell Computer Science 91.460 Java and Distributed Computing Prof. Karen Daniels Fall, 2000

Operator newOperator new

All (actually, most) objects are created with All (actually, most) objects are created with newnew newnew allocates memory allocates memory

Provides space for a copy of the class’ instance Provides space for a copy of the class’ instance variablesvariables

newnew initializes the object initializes the object Invokes the appropriate constructorInvokes the appropriate constructor

newnew returns a reference to the new object returns a reference to the new object Special cases: String and arraysSpecial cases: String and arrays

Page 45: UMass Lowell Computer Science 91.460 Java and Distributed Computing Prof. Karen Daniels Fall, 2000

Using new with ArraysUsing new with Arrays

You can declare an arrayYou can declare an array String airportNames[];String airportNames[];

You can initialize an array by listing elementsYou can initialize an array by listing elements String airportNames[] = { “SFO”, “BOS”, “LAX” };String airportNames[] = { “SFO”, “BOS”, “LAX” };

You can initialize an array with You can initialize an array with newnew String airportNames[] = new String[10];String airportNames[] = new String[10]; Note that this creates an array of Note that this creates an array of referencesreferences to Strings to Strings

Page 46: UMass Lowell Computer Science 91.460 Java and Distributed Computing Prof. Karen Daniels Fall, 2000

Command Line ArgumentsCommand Line Arguments

class class Test {Test { public static void public static void main(String[] main(String[] args) { ... } }args) { ... } }

Invocation: java Test This is a testInvocation: java Test This is a test Command line arguments are placed into the Command line arguments are placed into the

parameter of the main methodparameter of the main method The first argument after the className is placed The first argument after the className is placed

into the 0th element of the String array and so oninto the 0th element of the String array and so on I.e., args[0] is set to “This”, args[1] to “is”, ...I.e., args[0] is set to “This”, args[1] to “is”, ...

Page 47: UMass Lowell Computer Science 91.460 Java and Distributed Computing Prof. Karen Daniels Fall, 2000

package Definitionpackage Definition

A A packagepackage is a set of related classes is a set of related classes A A packagepackage is a mechanism for finding is a mechanism for finding

classes (and interfaces)classes (and interfaces) I.e., it is a directory mechanismI.e., it is a directory mechanism

A A packagepackage helps others use your classes helps others use your classes A A packagepackage provides a namespace provides a namespace [Classes are put into the no name package [Classes are put into the no name package

by default]by default]

Page 48: UMass Lowell Computer Science 91.460 Java and Distributed Computing Prof. Karen Daniels Fall, 2000

Making a packageMaking a package

Build the class with public methodsBuild the class with public methods So that it can be used by classes outside of your packageSo that it can be used by classes outside of your package

Put the class into a packagePut the class into a package Add a Add a packagepackage statement to (top of) the class definition statement to (top of) the class definition

filefile Syntax: Syntax: packagepackage packageName; packageName;

Compile the class and place it into the appropriate Compile the class and place it into the appropriate directory structure (with the -d compiler switch)directory structure (with the -d compiler switch) The classes directoryThe classes directory

Page 49: UMass Lowell Computer Science 91.460 Java and Distributed Computing Prof. Karen Daniels Fall, 2000

import Statementsimport Statements

Mechanism for helping the compiler find Mechanism for helping the compiler find other classesother classes

Becomes a shorthand mechanismBecomes a shorthand mechanism Can refer to class by simple name rather than Can refer to class by simple name rather than

full “path”full “path” Not required if can guarantee that all Not required if can guarantee that all

needed .class files in the same directory needed .class files in the same directory

Page 50: UMass Lowell Computer Science 91.460 Java and Distributed Computing Prof. Karen Daniels Fall, 2000

import Statements (concluded)import Statements (concluded)

Three forms:Three forms: import packageName.className;import packageName.className; import packageName.interfaceName;import packageName.interfaceName; import packageName.*;import packageName.*;

Page 51: UMass Lowell Computer Science 91.460 Java and Distributed Computing Prof. Karen Daniels Fall, 2000

Class String and LiteralsClass String and Literals

Using a string literal automatically creates Using a string literal automatically creates an instance of class String with the value of an instance of class String with the value of that string literalthat string literal Don’t have to use new (but you can)Don’t have to use new (but you can)

Page 52: UMass Lowell Computer Science 91.460 Java and Distributed Computing Prof. Karen Daniels Fall, 2000

Adding Strings Adding Strings

When the compiler sees an + operator and one of When the compiler sees an + operator and one of the operands is a String (or a string literal), it will the operands is a String (or a string literal), it will attempt to convert the other operand to a Stringattempt to convert the other operand to a String If the other operand is an Object, it will call the If the other operand is an Object, it will call the

object’s toString() methodobject’s toString() method If the other operand is a primitive type, it will “wrap” If the other operand is a primitive type, it will “wrap”

it and then invoke the wrapper’s toString() methodit and then invoke the wrapper’s toString() method Example: 1 + “2” = “12”Example: 1 + “2” = “12”