An Overview of Java Part III - Classes and Objectsmason.gmu.edu/~jbaldo/432Lec08B-JavaII.pdf · An...

48
An Overview of Java Part III - Classes and Objects Jeff Offutt Roger Alexander http://www.ise.gmu.edu/~offutt/ SWE 432 Design and Implementation of Software for the Web Fall 2007 : Created 432Lec08-Java.ppt – cut most of JavaI and JavaII, then merged. © Alexander & Offutt, 1999-2007 2 Organization III. Classes in Java IV. Exceptions V. Inheritance VI. JavaDoc VII. Some Useful Libraries

Transcript of An Overview of Java Part III - Classes and Objectsmason.gmu.edu/~jbaldo/432Lec08B-JavaII.pdf · An...

Page 1: An Overview of Java Part III - Classes and Objectsmason.gmu.edu/~jbaldo/432Lec08B-JavaII.pdf · An Overview of Java Part III - Classes and Objects Jeff Offutt Roger Alexander offutt

An Overview of JavaPart III - Classes and Objects

Jeff OffuttRoger Alexander

http://www.ise.gmu.edu/~offutt/

SWE 432Design and Implementation of Software for the Web

Fall 2007 : Created 432Lec08-Java.ppt – cut most of JavaI and JavaII, then merged.

© Alexander & Offutt, 1999-2007 2

Organization

III. Classes in Java

IV. Exceptions

V. Inheritance

VI. JavaDoc

VII. Some Useful Libraries

Page 2: An Overview of Java Part III - Classes and Objectsmason.gmu.edu/~jbaldo/432Lec08B-JavaII.pdf · An Overview of Java Part III - Classes and Objects Jeff Offutt Roger Alexander offutt

© Alexander & Offutt, 1999-2007 3

Part III - Classes in Java

© Alexander & Offutt, 1999-2007 4

Java Classes• The class is the basic data abstraction mechanism in Java

• Classes combine records, data structures, and information hiding into one structure

• Classes are used to construct Abstract Data Types (ADTs)

Page 3: An Overview of Java Part III - Classes and Objectsmason.gmu.edu/~jbaldo/432Lec08B-JavaII.pdf · An Overview of Java Part III - Classes and Objects Jeff Offutt Roger Alexander offutt

© Alexander & Offutt, 1999-2007 5

Java Classes (cont’d)

Class Characteristics:

• Name: Used to declare objects of the class• State definition: Collection of variables (fields)• Behavior: Collection of methods• Semantics: Constraints on state-space and behavior• Access Levels: Private, protected, public, default

© Alexander & Offutt, 1999-2007 6

Java Classes (cont’d)

A Java class defines a set of values and a set of operations. Together, these form a type. An instance, or object, of that class is a variable of the class type.

Watch W = new Watch ();

W is an instance of the class Watch.

Page 4: An Overview of Java Part III - Classes and Objectsmason.gmu.edu/~jbaldo/432Lec08B-JavaII.pdf · An Overview of Java Part III - Classes and Objects Jeff Offutt Roger Alexander offutt

© Alexander & Offutt, 1999-2007 7

Java Classes (cont’d)

A class is a type constructor:

• Similar in use to an Ada package, a Modula-2 module, or a C++ class

• A class is more than a type ... it is an encapsulation unit

• A class is used in place of type definitions and collections of functions

© Alexander & Offutt, 1999-2007 8

Java Classes (cont’d)Classes are used to create objects

• Objects have:– identity : name– state : a set of values for the data members– behavior: sequence of operations

• Objects may be dynamically allocated• References to objects can be passed as parameters to methods

Page 5: An Overview of Java Part III - Classes and Objectsmason.gmu.edu/~jbaldo/432Lec08B-JavaII.pdf · An Overview of Java Part III - Classes and Objects Jeff Offutt Roger Alexander offutt

© Alexander & Offutt, 1999-2007 9

Java Classes (cont’d)Abstract Data Types

A class with a private representation and a public set of operations is used to implement abstract data types

Fraction myFraction;myFraction = new Fraction ();

© Alexander & Offutt, 1999-2007 10

Java Classes (cont’d)

Class

variablesmethods

instanceobject 1

declare

instanceobject N

instanceobject 2

declaredeclare

Fraction

int Numeratorint DenominatorAdd ()Multiply ()

(Type)

F1

declare

NumDen

allocate F2

declare

NumDen

allocate

Page 6: An Overview of Java Part III - Classes and Objectsmason.gmu.edu/~jbaldo/432Lec08B-JavaII.pdf · An Overview of Java Part III - Classes and Objects Jeff Offutt Roger Alexander offutt

© Alexander & Offutt, 1999-2007 11

Java Classes (cont’d)

• Classes can be grouped together to form packages

• Packages are usually used to implement design-level components

• All classes in the same package are usually stored in the same directory

• The directory has the same name as the package

• Examplepackage myADTs;public class queueADT { } // part of package myADTs

© Alexander & Offutt, 1999-2007 12

Java Classes (cont’d)The Class Definition

• Class head: Access, keyword class and class tag name• Class body: Variables and methods enclosed in curly braces

public class Fraction { ... }Fraction myFraction, yourFraction;

Page 7: An Overview of Java Part III - Classes and Objectsmason.gmu.edu/~jbaldo/432Lec08B-JavaII.pdf · An Overview of Java Part III - Classes and Objects Jeff Offutt Roger Alexander offutt

© Alexander & Offutt, 1999-2007 13

Java Classes (cont’d)Variable Members

Often referred to as instance variables

public class Fraction{

private int Numerator;private int Denominator;

}

© Alexander & Offutt, 1999-2007 14

Initial Values• Class instance variables can be initialized in its declaration:

double pi = 3.14159;

• If not, Java assigns default values to instance variables, dependent upon the type of the variable

• Note that local variables in methods, constructors, static initializers, and instance initializers do not get default values

Page 8: An Overview of Java Part III - Classes and Objectsmason.gmu.edu/~jbaldo/432Lec08B-JavaII.pdf · An Overview of Java Part III - Classes and Objects Jeff Offutt Roger Alexander offutt

© Alexander & Offutt, 1999-2007 15

Initial Values (cont’d)Typeboolean

char

integer (byte, short, int, long)

floating point

object reference

Initial Valuefalse

`/u0000’

0

+0.0f or +0.0d

null

© Alexander & Offutt, 1999-2007 16

Java Classes (cont’d)

Variable Members

Classes may be self-referential, through the class tag name

public class List{

private int Value;private List Next;

}

Page 9: An Overview of Java Part III - Classes and Objectsmason.gmu.edu/~jbaldo/432Lec08B-JavaII.pdf · An Overview of Java Part III - Classes and Objects Jeff Offutt Roger Alexander offutt

© Alexander & Offutt, 1999-2007 17

Java Classes (cont’d)

Methods, or Member Functions

Operations to be performed on class objects are defined as member functions

public class Fraction{

public Fraction (int Num, int Den) { … }public void Add (Fraction Right) { … }public void Multiply (Fraction Right) { … }public void PrintFrac () { … }

}

© Alexander & Offutt, 1999-2007 18

Java Classes (cont’d)

Fraction Class

public class Fraction{

// variable membersprivate int Numerator; // Only available to member functionsprivate int Denominator;// methodspublic Fraction (int Num, int Den) { … } // Constructorpublic void Add (Fraction Right) { … } // F1 = F1 + F2public void Multiply (Fraction Right) { … } // F1 = F1 * F2public void PrintFrac () { … }

}

Page 10: An Overview of Java Part III - Classes and Objectsmason.gmu.edu/~jbaldo/432Lec08B-JavaII.pdf · An Overview of Java Part III - Classes and Objects Jeff Offutt Roger Alexander offutt

© Alexander & Offutt, 1999-2007 19

Variable Characteristics• Name• Type

(primitive or user-defined)

• Optional access specifier(public, private, or protected)

• Per-Instance (instance variables) or per-Class (class variables) (static)

• May be constant( final )

© Alexander & Offutt, 1999-2007 20

Method Characteristics

• Name• Return Type

(primitive, user-defined, or void)

• Optional access Specifier(public, protected, or private)

• Body (code)• Per-instance (instance methods) or per-Class (class

methods) (static)

Page 11: An Overview of Java Part III - Classes and Objectsmason.gmu.edu/~jbaldo/432Lec08B-JavaII.pdf · An Overview of Java Part III - Classes and Objects Jeff Offutt Roger Alexander offutt

© Alexander & Offutt, 1999-2007 21

Access Control• All variables and methods of a class are available to methods

inside the class

• Four access specifiers define accessibility by other classes:1. public - members are accessible anywhere the class is accessible2. private - members are accessible only inside the class3. protected - accessible by subclasses (through inheritance) and within the

same package4. default – next slide …

© Alexander & Offutt, 1999-2007 22

Access Control (cont’d)

4. default: Members with no access specifier are accessible to code in the containing class, and are inherited by classes defined in the same package

Page 12: An Overview of Java Part III - Classes and Objectsmason.gmu.edu/~jbaldo/432Lec08B-JavaII.pdf · An Overview of Java Part III - Classes and Objects Jeff Offutt Roger Alexander offutt

© Alexander & Offutt, 1999-2007 23

Class 4

Access Control (cont’d)

Class 1

inheritance

Class 3

Class 2

Package

Class 5

private members

default

protected members

public members

© Alexander & Offutt, 1999-2007 24

Creating Objects• In Java, variables of user defined types are pointers, or

references, to the actual type instance (i.e. object)

• References must be declared and initialized with an instance before use

• An object instance is created using the new operator

Page 13: An Overview of Java Part III - Classes and Objectsmason.gmu.edu/~jbaldo/432Lec08B-JavaII.pdf · An Overview of Java Part III - Classes and Objects Jeff Offutt Roger Alexander offutt

© Alexander & Offutt, 1999-2007 25

Creating Objects (cont’d)

• Example:Fraction F1;F1 = new Fraction ( );F1.PrintFrac ( ); // oops!!! Num=0, Den=0 …

• How do we properly initialize state variables?

© Alexander & Offutt, 1999-2007 26

Three Categories of Methods1) Constructors: Called automatically when an object is created.

Usually used to give initial values to the variables.

2) Mutators: Modify the state of the object (changes the value of one or more variables).

3) Accessors: Examine the state of the object (returns current values of state variables).

Page 14: An Overview of Java Part III - Classes and Objectsmason.gmu.edu/~jbaldo/432Lec08B-JavaII.pdf · An Overview of Java Part III - Classes and Objects Jeff Offutt Roger Alexander offutt

© Alexander & Offutt, 1999-2007 27

Constructors• Newly created objects are always given initial values.

• Variables can be initialized with a value when they are created.But often, more is needed than simple initialization.

• Constructors are special routines that establish an initial state for an object.

© Alexander & Offutt, 1999-2007 28

Rules for Constructors• Have the same name as their class

• Have zero or more parameters

• Have no return type

• Invoked …– after instance variables of newly created class instance have been assigned

their default initial values– after initialization during declaration (int i=0;)

Page 15: An Overview of Java Part III - Classes and Objectsmason.gmu.edu/~jbaldo/432Lec08B-JavaII.pdf · An Overview of Java Part III - Classes and Objects Jeff Offutt Roger Alexander offutt

© Alexander & Offutt, 1999-2007 29

Constructor Examples

public Fraction () // constructor{ // Constructor with no arguments is called a default constructor

Numerator = 0;Denominator = 1;

}

public Fraction (int Num, int Den) // constructor{

Numerator = Num;Denominator = Den;

}

F1 = new Fraction ();F2 = new Fraction (3, 4);

© Alexander & Offutt, 1999-2007 30

Constructor Examples• May invoke other constructors in same class via this (explicit

constructor invocation)– Must be the first statement– May pass parameters

• Example:public Fraction ( ) // default constructor{

this (0, 1);}

Page 16: An Overview of Java Part III - Classes and Objectsmason.gmu.edu/~jbaldo/432Lec08B-JavaII.pdf · An Overview of Java Part III - Classes and Objects Jeff Offutt Roger Alexander offutt

© Alexander & Offutt, 1999-2007 31

Importance of Constructors

• Ensure that instances are in a consistent initial state

• If no constructors, a default constructor is provided that supplies default values

• Some classes will have no reasonable default state without constructors

• A non-public constructor restricts who can create instances of a class

© Alexander & Offutt, 1999-2007 32

Mutator and Accessor Methods

• Methods contain the code that defines the object’s behavior (semantics)

• Methods having public access specifier constitute the class interface

• Methods are invoked as operations on objects with the dot operator:

F1.Add (F2)

Page 17: An Overview of Java Part III - Classes and Objectsmason.gmu.edu/~jbaldo/432Lec08B-JavaII.pdf · An Overview of Java Part III - Classes and Objects Jeff Offutt Roger Alexander offutt

© Alexander & Offutt, 1999-2007 33

Methods (cont’d)

• Methods may have a return type, or no return type (void)

• Methods may have an access specifier(public, protected, private)

© Alexander & Offutt, 1999-2007 34

Method Examples

public void Add (Fraction Right){ // Mutator

Numerator = Numerator + Right.Numerator;}

public void Multiply (Fraction Right){ // Mutator

Numerator = Numerator * Right.Numerator;Denominator = Denominator * Right.Denominator;

}

public void PrintFrac (){ // Accessor

System.out.println (Numerator + " / " + Denominator);}

Page 18: An Overview of Java Part III - Classes and Objectsmason.gmu.edu/~jbaldo/432Lec08B-JavaII.pdf · An Overview of Java Part III - Classes and Objects Jeff Offutt Roger Alexander offutt

© Alexander & Offutt, 1999-2007 35

Four Special Common Methods

1) toString : Converts an object to a stringUsed by print and println

2) equals : Compares two objects

3) clone: Makes a copy

4) main : Main method

© Alexander & Offutt, 1999-2007 36

toString Method• Returns a string version of the object’s values• Called implicitly by System.out.println• Example:

public String toString (){

return (Numerator + " / " + Denominator);}

Fraction f1 = new (3, 7);System.out.println (f1);

Page 19: An Overview of Java Part III - Classes and Objectsmason.gmu.edu/~jbaldo/432Lec08B-JavaII.pdf · An Overview of Java Part III - Classes and Objects Jeff Offutt Roger Alexander offutt

© Alexander & Offutt, 1999-2007 37

equals Method

• Compares two objects

• Standard signature, parameter is type Object

• Use instanceof to see if parameter is correct type

© Alexander & Offutt, 1999-2007 38

Object Class

All classes inherit from the Java built-in class Object

Object

Fraction Watch String

Assign up, cast down

An object of type Fraction can be assigned to an Object, but not vice-versa

Object O = new Object ();Fraction f = new Fraction ();

O = f; // Assign upF = (Fraction) O; // Cast down

Page 20: An Overview of Java Part III - Classes and Objectsmason.gmu.edu/~jbaldo/432Lec08B-JavaII.pdf · An Overview of Java Part III - Classes and Objects Jeff Offutt Roger Alexander offutt

© Alexander & Offutt, 1999-2007 39

equals Method Example

public boolean equals (Object Right) // Matches any object{

if (!(Right instanceof Fraction)) // Is Right a Fraction?return (false);

Fraction rhs = (Fraction) Right; // Cast to Fractionreturn (Numerator == rhs.Numerator &&

Denominator == rhs.Denominator);}

Fraction f1 = new (3, 7);Fraction f2 = new (3, 7);if (f1.equals (f2))

. . .

© Alexander & Offutt, 1999-2007 40

clone Method• Copies all values• Example:

public Object clone (){

Fraction newf = new Fraction ();newf.Numerator = Numerator;newf.Denominator = Denominatorreturn (newf); // implicit "assign up" to Object

}

Fraction f2 = (Fraction) f1.clone(); // Must cast

Page 21: An Overview of Java Part III - Classes and Objectsmason.gmu.edu/~jbaldo/432Lec08B-JavaII.pdf · An Overview of Java Part III - Classes and Objects Jeff Offutt Roger Alexander offutt

© Alexander & Offutt, 1999-2007 41

main Method• Every class can have a main method

– Called when java ClassName is executed– Ignored when ClassName is used in another program

• Use to test classes– Put a main () inside every class– Call every method at least once

© Alexander & Offutt, 1999-2007 42

main Method Example

public static void main (String argv[]){

Fraction f1, f2;

f1 = new Fraction (1, 4);f2 = new Fraction (3, 4);

f1.PrintFrac ();System.out.println (f2); // Implicit call to f2.toString()f1.Add (f2);System.out.println (f1);f1.Multiply (f2);System.out.println (f1);

}

Page 22: An Overview of Java Part III - Classes and Objectsmason.gmu.edu/~jbaldo/432Lec08B-JavaII.pdf · An Overview of Java Part III - Classes and Objects Jeff Offutt Roger Alexander offutt

© Alexander & Offutt, 1999-2007 43

Class (Static) Variables• Only one per class, not per instance object• All instance objects reference the same copy• Static variables are initialized before any static variable is used

or any method is run

public class Fraction{

// Should be incremented in constructor methodsprivate static int CurNumFracs = 0;

…}

© Alexander & Offutt, 1999-2007 44

Class (Static) Variables (cont’d)

Fraction

F1

declare

NumDen

allocate F2

declare

NumDen

allocate

CurNumFracs

Page 23: An Overview of Java Part III - Classes and Objectsmason.gmu.edu/~jbaldo/432Lec08B-JavaII.pdf · An Overview of Java Part III - Classes and Objects Jeff Offutt Roger Alexander offutt

© Alexander & Offutt, 1999-2007 45

Class (Static) Methods

• Effects all instantiated objects of the class, not a specific object

• Typically performs general tasks for all objects of a class

• Can only access static variables and other staticmethods

• If public, accessed from outside class using the classname rather than object reference:

<class name>.<method name> ()

© Alexander & Offutt, 1999-2007 46

Static Method Example

public class Fraction{

public static int getNumFracs (){

return (CurNumFracs);}

. . .}

N = Fraction.GetNumFracs ();

Page 24: An Overview of Java Part III - Classes and Objectsmason.gmu.edu/~jbaldo/432Lec08B-JavaII.pdf · An Overview of Java Part III - Classes and Objects Jeff Offutt Roger Alexander offutt

© Alexander & Offutt, 1999-2007 47

Static Initialization Blocks• Used to initialize static variables and set up other resources, as

necessary

• Consists of one or more statements

• Cannot throw exceptions

• May only call static methods

• Must catch all exceptions thrown by called methods

Skip, 432 …

© Alexander & Offutt, 1999-2007 48

Static Initialization Blocks (cont’d)• May be more than one static initializer in a class. If so, they are

executed in order of appearance.

• Initializers for static variables cannot invoke methods that throw checked exceptions.

• Initializers are run when class is loaded (which is unpredictable).

Skip, 432 …

Page 25: An Overview of Java Part III - Classes and Objectsmason.gmu.edu/~jbaldo/432Lec08B-JavaII.pdf · An Overview of Java Part III - Classes and Objects Jeff Offutt Roger Alexander offutt

© Alexander & Offutt, 1999-2007 49

finalize

• Special method written by programmer• Called automatically when object is being destructed• Used to release resources held by object, and any last-

minute cleanup• Cannot predict when it will execute• Might not execute at all!

Skip, 432 …

© Alexander & Offutt, 1999-2007 50

finalize (cont’d)

An Example:

protected void finalize () throws throwable{

super.finalize (); // must call this first!// Put cleanup code here.

}

Skip, 432 …

Page 26: An Overview of Java Part III - Classes and Objectsmason.gmu.edu/~jbaldo/432Lec08B-JavaII.pdf · An Overview of Java Part III - Classes and Objects Jeff Offutt Roger Alexander offutt

© Alexander & Offutt, 1999-2007 51

Garbage Collection• When an object is no longer referenced, the space it occupies is

automatically reclaimed

• Eliminates burden of having to manage memory

• Eliminates possibility of memory leaks and dangling references

© Alexander & Offutt, 1999-2007 52

Part IV - Exceptions

Page 27: An Overview of Java Part III - Classes and Objectsmason.gmu.edu/~jbaldo/432Lec08B-JavaII.pdf · An Overview of Java Part III - Classes and Objects Jeff Offutt Roger Alexander offutt

© Alexander & Offutt, 1999-2007 53

Errors and Exceptions• During execution, “stuff” happens• Many kinds of errors• Many kinds of exceptional situations• Varying degrees of severity• Code to handle errors adds complexity

– Often, more code required to handle errors than the original function

• Code to handle errors adds robustness– program can behave reasonably in more situations

© Alexander & Offutt, 1999-2007 54

Java Exceptions• A clean way to check for exceptional conditions

• Mechanism to signal programmer-defined exceptions

• Exceptions that a method can signal part of the signature

• Automatically checked by compiler

Page 28: An Overview of Java Part III - Classes and Objectsmason.gmu.edu/~jbaldo/432Lec08B-JavaII.pdf · An Overview of Java Part III - Classes and Objects Jeff Offutt Roger Alexander offutt

© Alexander & Offutt, 1999-2007 55

Java Exceptions• Handlers attached to explicit “try” blocks

• Terminates execution of block

• Exceptions propagated dynamically

• Exceptions are named objects

• Can be raised explicitly and implicitly

© Alexander & Offutt, 1999-2007 56

Java Exceptions -- Five Parts

1) try : A block of code that can catch exceptions

2) throw : Explicitly signal or raise an exception

3) catch : Code to handle a named exception

4) finally : A special handler (rules later)

5) throws : Exceptions a method can throw

Page 29: An Overview of Java Part III - Classes and Objectsmason.gmu.edu/~jbaldo/432Lec08B-JavaII.pdf · An Overview of Java Part III - Classes and Objects Jeff Offutt Roger Alexander offutt

© Alexander & Offutt, 1999-2007 57

Exceptions – General Form

try{

// block of code to be monitored for exceptions}catch (ExceptionType1 obj1){

// exception handler for ExceptionType1}catch (ExceptionType2 obj2){

// exception handler for ExceptionType2}finally{

// special exception handler}

© Alexander & Offutt, 1999-2007 58

Exceptions – RulesIf an exception is thrown, control passes to the innermost enclosing try block that has a catch handler for that type of exception.

If there is no handler, control propagates up through main ()until a handler is found, or until the program terminates.

Page 30: An Overview of Java Part III - Classes and Objectsmason.gmu.edu/~jbaldo/432Lec08B-JavaII.pdf · An Overview of Java Part III - Classes and Objects Jeff Offutt Roger Alexander offutt

© Alexander & Offutt, 1999-2007 59

Exceptions – Example

class ExcExample{

public static void main (String args[]){

int d, a;try{ // monitor a block of code.

d= 0;a = 42 / d;System.out.println (“This will never be printed.”);

}catch (ArithmeticException e){ // catch divide-by-zero error

System.out.println (“Division by zero.”);}System.out.println (“After catch.”);

}}

© Alexander & Offutt, 1999-2007 60

Exceptions – Throwing Your Own

public void Add (Fraction Right){

try{

Numerator = Numerator + Right.Numerator;if (Denominator != Right.Denominator)

throw new ArithmeticException ();}catch (ArithmeticException e){

System.out.println ("Fraction add error:Denominators must be the same.");

}}

Page 31: An Overview of Java Part III - Classes and Objectsmason.gmu.edu/~jbaldo/432Lec08B-JavaII.pdf · An Overview of Java Part III - Classes and Objects Jeff Offutt Roger Alexander offutt

© Alexander & Offutt, 1999-2007 61

Exceptions – Throwing Your Own

public void Add (Fraction Right) throws ArithmeticException{

Numerator = Numerator + Right.Numerator;if (Denominator != Right.Denominator)

throw new ArithmeticException ();

}

try {f1.Add (f2);

}catch {

…}

© Alexander & Offutt, 1999-2007 62

finally

• Executes a section of code even when an exception is not thrown

• Used to clean up internal state and release resources

• Used to clean up after break, continue, and return

Page 32: An Overview of Java Part III - Classes and Objectsmason.gmu.edu/~jbaldo/432Lec08B-JavaII.pdf · An Overview of Java Part III - Classes and Objects Jeff Offutt Roger Alexander offutt

© Alexander & Offutt, 1999-2007 63

finallyA finally block is executed when:

1) try block executes without exception

2) exception occurs in the try block, but is not caught• exception propagates after finally block

3) exception occurs in the try block, and is caught• finally block executes after the catch block

© Alexander & Offutt, 1999-2007 64

Java’s Built-in Exceptions

• ArithmeticException• ArrayIndexOutOfBoundsException• ArrayStoreException• ClassCastException• IllegalArgumentException• IllegalMonitorStateException• IllegalStateException• IllegalThreadStateException• IndexOutOfBoundsException• NegativeArraySizeException

• NullPointerException• NumberFormatException• SecurityException• StringIndexOutOfBounds• ClassNotFoundException• CloneNotSupportedException• IllegalAccessException• InstantiationException• InterruptedException• NoSuchFieldException• NoSuchMethodException

Page 33: An Overview of Java Part III - Classes and Objectsmason.gmu.edu/~jbaldo/432Lec08B-JavaII.pdf · An Overview of Java Part III - Classes and Objects Jeff Offutt Roger Alexander offutt

© Alexander & Offutt, 1999-2007 65

Making Your Own Exceptions• All exceptions are represented by a specific class that extends

class Exception

• Create a class for each type of exception that can occur

• Add variables to capture information to describe exception

© Alexander & Offutt, 1999-2007 66

Making Your Own Exceptions

class MyException extends Exception{

private int detail;

MyException (int a){

detail = a;}

public String toString (){

return “MyException[“ + detail + “]”;}

}

Page 34: An Overview of Java Part III - Classes and Objectsmason.gmu.edu/~jbaldo/432Lec08B-JavaII.pdf · An Overview of Java Part III - Classes and Objects Jeff Offutt Roger Alexander offutt

© Alexander & Offutt, 1999-2007 67

Making Your Own Exceptions

class ExcDemo {static void compute (int a) throws MyException {

System.out.println (“Called compute (“ + a + “)”);if (a > 10)

throw new MyException (a);System.out.println (“Normal exit”);

}

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

compute (1);compute (20);

} catch (MyException e) {System.out.println (“Caught “ + e);

}}

}

© Alexander & Offutt, 1999-2007 68

Part V - Inheritance

Page 35: An Overview of Java Part III - Classes and Objectsmason.gmu.edu/~jbaldo/432Lec08B-JavaII.pdf · An Overview of Java Part III - Classes and Objects Jeff Offutt Roger Alexander offutt

© Alexander & Offutt, 1999-2007 69

Inheritance• If class A inherits from class B, then A has all methods and

variables that B has

• A can also add new methods and variables

• This is a technique for abstraction

© Alexander & Offutt, 1999-2007 70

Basic Terminology

Class Member Functions(methods)

Instantiate

ObjectHas

Identity

Define

Behavior

Yields

State

Page 36: An Overview of Java Part III - Classes and Objectsmason.gmu.edu/~jbaldo/432Lec08B-JavaII.pdf · An Overview of Java Part III - Classes and Objects Jeff Offutt Roger Alexander offutt

© Alexander & Offutt, 1999-2007 71

Inheritance Terminology

• Parent class and Superclass refer to the class from which another inherits

• Child class, derived class, and subclass refer to a class that inherits from one or more classes

© Alexander & Offutt, 1999-2007 72

What is “Object-oriented”?

Object-oriented programming language

Object-based programming language

Object-oriented design

Page 37: An Overview of Java Part III - Classes and Objectsmason.gmu.edu/~jbaldo/432Lec08B-JavaII.pdf · An Overview of Java Part III - Classes and Objects Jeff Offutt Roger Alexander offutt

© Alexander & Offutt, 1999-2007 73

Encapsulation(data hiding)

Clients cannot know about or depend on the implementation of the class

© Alexander & Offutt, 1999-2007 74

Data Abstraction

• Creation of a new data type from previously existing components

• Abstract Data Type:– Set of values– Connection of operations– Semantics of operations

Page 38: An Overview of Java Part III - Classes and Objectsmason.gmu.edu/~jbaldo/432Lec08B-JavaII.pdf · An Overview of Java Part III - Classes and Objects Jeff Offutt Roger Alexander offutt

© Alexander & Offutt, 1999-2007 75

Inheritance

Allows common features of many classes to be defined in one class

A child class, derived class, or subclass

inherits

from aparent class, base class, or super class

© Alexander & Offutt, 1999-2007 76

Inheritance (2)

• Enhance derived features (overriding)• Restrict derived features (not in Java)• Add new features (extension)

A derived class has everything its parent has, plus it can:

Page 39: An Overview of Java Part III - Classes and Objectsmason.gmu.edu/~jbaldo/432Lec08B-JavaII.pdf · An Overview of Java Part III - Classes and Objects Jeff Offutt Roger Alexander offutt

© Alexander & Offutt, 1999-2007 77

Polymorphism

• The same variable can have different types depending on the program execution

• If B inherits from A, then an object of type B can be used when an object of type A is expected

• If both A and B define the same method M (B overrides A), then the same statement will sometimes call A’s version of M, and sometimes B’s version

© Alexander & Offutt, 1999-2007 78

Subtype and Subclass Inheritance

• Subtype Inheritance: If B inherits from A, any object of type B can be substituted for an object of type A– A laptop “is a” special type of computer– Called substitutability

• Subclass Inheritance: Objects of type B may not be substituted for objects of type A– Objects of B may not be “type compatible”

Page 40: An Overview of Java Part III - Classes and Objectsmason.gmu.edu/~jbaldo/432Lec08B-JavaII.pdf · An Overview of Java Part III - Classes and Objects Jeff Offutt Roger Alexander offutt

© Alexander & Offutt, 1999-2007 79

Inheritance Example

ClockhourminutesecondsetTime()getTime()

AlarmClockModealarmHouralarmMinutealarmModesetAlarm()getAlarm()

WatchmonthdayyearmodesetDate()getDate()

WallClocksetTime()getTime()

Inherits from

© Alexander & Offutt, 1999-2007 80

Inheritance Example (2)

class Clock{

private int hour, minute, second;

public setTime (int h, int m, int s){

hour = h;minute = m;second = s;

}…

} // end Clock

class Watch extends Clock{

private int month, day, year;private String mode;

…public setTime (int h, int m, int s, String d){

super.setTime (h, m, s)mode = d;

}} // end Watch

Page 41: An Overview of Java Part III - Classes and Objectsmason.gmu.edu/~jbaldo/432Lec08B-JavaII.pdf · An Overview of Java Part III - Classes and Objects Jeff Offutt Roger Alexander offutt

© Alexander & Offutt, 1999-2007 81

Part VI – Java Doc

© Alexander & Offutt, 1999-2007 82

javadoc Utility• Documentation comments can be embedded into Java programs

/** documentation comment **/

• The javadoc program will create HTML documentation, using javadoc comments

• javadoc comments can include javadoc “tags” to specify certain information

Page 42: An Overview of Java Part III - Classes and Objectsmason.gmu.edu/~jbaldo/432Lec08B-JavaII.pdf · An Overview of Java Part III - Classes and Objects Jeff Offutt Roger Alexander offutt

© Alexander & Offutt, 1999-2007 83

javadoc Tags

• @author : identifies the author of a class• @exception : Identifies an exception thrown by a method• @see : Specifies a link to another topic• @param : Documents a method’s parameter• @return : Documents a method’s return value• @version : Specifies the version of a class• HTML tags may also be used

javadoc -author -version ClassName.java

© Alexander & Offutt, 1999-2007 84

javadoc Example

/** ********************************************************** Fraction implements a Fraction ADT.* @author Jeff Offutt* @version 1.2, 1/99********************************************************* **/

/** ********************************************************** Mutator : Adds two fractions, F1 = F1+F2. <BR>* Precondition: Both denominators must be the same. <BR>* This is checked with the exception ArithmeticException.* @param Right Fraction right-hand-side* @return None********************************************************* **/

Page 43: An Overview of Java Part III - Classes and Objectsmason.gmu.edu/~jbaldo/432Lec08B-JavaII.pdf · An Overview of Java Part III - Classes and Objects Jeff Offutt Roger Alexander offutt

© Alexander & Offutt, 1999-2007 85

Part VII – Some Useful Libraries

© Alexander & Offutt, 1999-2007 86

Java Collections Framework (Java 1.5)• http://java.sun.com/j2se/1.5.0/docs/guide/collections/• http://g.oswego.edu/dl/classes/collections/

• A collection is an object that represents a group of objects (such as the familiar Vector class)

• A collections framework is a unified architecture for representing and manipulating collections, allowing them to be manipulated independently of the details of their representation

• Contains most of the familiar ADTs• … and lots of unfamiliar ADTs

Page 44: An Overview of Java Part III - Classes and Objectsmason.gmu.edu/~jbaldo/432Lec08B-JavaII.pdf · An Overview of Java Part III - Classes and Objects Jeff Offutt Roger Alexander offutt

© Alexander & Offutt, 1999-2007 87

Java Interface & Generic• A Java interface defines a type, including definitions of variables

and methods, but does not implement methods• Used to help ensure consistency

public interface Set<E> extends Collection<E>{ //Basic operations

int size ();boolean isEmpty (); boolean contains (Object element);boolean add (E element);boolean remove (Object element);

}

Keyword implies methods have no bodies

Generic – can be used with arbitrary type

(Formal type parameter)

Set<String> strSet = new Set<String>();Set<Integer> intSet = new Set<Integer>();

strSet.add (“George”);strSet.add (“Burdell”);intSet.add (new Integer (1935));intSet.add (“oops”); // ERROR !!!

Set can only hold Strings

Run-time type checking

© Alexander & Offutt, 1999-2007 88

Nine Collection Interfaces• Collection• Five interfaces extend Collection

– Set– List– SortedSet– Queue– BlockingQueue

• Three mapping interfaces– Map– SortedMap– ConcurrentMap

Page 45: An Overview of Java Part III - Classes and Objectsmason.gmu.edu/~jbaldo/432Lec08B-JavaII.pdf · An Overview of Java Part III - Classes and Objects Jeff Offutt Roger Alexander offutt

© Alexander & Offutt, 1999-2007 89

Classes that Implement Collection Interfaces

LinkedHashMapTreeMapHashMapMap

LinkedListArrayListList

LinkedHashSetTreeSetHashSetSet

Interfaces

Hash Table+

Linked List

Linked List

Balanced Tree

Resizable Array

Hash Table

Implementations

© Alexander & Offutt, 1999-2007 90

Collections• public interface Collection<E> extends Iterable<E>• Root interface in the collection inheritance hierarchy• Methods (partial list - also available in all collections)

– boolean add (E o) // adds one element– void clear () // removes all elements– boolean contains (Object o) // true if o is in collection– boolean equals (Object o) // compares two collections– boolean isEmpty () // true if no elements– iterator iterator () // returns an iterator– boolean remove (Object o) // removes o– int size () // number of elements– <T> T [ ] toArray (T[ ] a) // returns an array of elements of type T

Page 46: An Overview of Java Part III - Classes and Objectsmason.gmu.edu/~jbaldo/432Lec08B-JavaII.pdf · An Overview of Java Part III - Classes and Objects Jeff Offutt Roger Alexander offutt

© Alexander & Offutt, 1999-2007 91

Interface Iterator <E>• Allows programs to access every member from a collection, in

order• Most collection classes implement Iterator• Methods

– boolean hasNext () // true if iterator has more elements– E next () // returns the next element– void remove () // removes the last element returned

Iterator <String> strSetIter = new strSet.Iterator <String> ();while strSetIter.hasNext (){

System.out.println (strSetIter.next () );}

© Alexander & Offutt, 1999-2007 92

public class HashMap <K,V>• Maps keys to values

– K is the type of the key– V is the type of the values

• HashMap <String, String> is useful for associating parameter names with values in web applications

• Methods– Boolean containsKey (Object key) // true if a mapping for key is present– Boolean containsValue (Object value) // true if value is present– V Get (Object key) // returns value for key– V put (K key, V value) // associates value with key, returns previous value– V remove (Object key) // removes value associated with key, returns

previous value– Collection<V> values () // returns all values

Page 47: An Overview of Java Part III - Classes and Objectsmason.gmu.edu/~jbaldo/432Lec08B-JavaII.pdf · An Overview of Java Part III - Classes and Objects Jeff Offutt Roger Alexander offutt

© Alexander & Offutt, 1999-2007 93

Regular Expressions• A regular expression is a compact representation of a set of

strings– a* – any string of any number of ‘a’s (a, aa, aaa, aaaa, …)– [46]32 – either “432” or “632”– [sc][wsy][e s] – “swe” or “cs ” or “sys” (also “cws”, etc.)– \\\\.*$ – Java comment, two backslashes, any sequence of characters,

followed by an end of line

• http://java.sun.com/j2se/1.5.0/docs/api/java/util/regex/Pattern.html for a full description

• Java includes a built-in library for handling regular expressions

import com.sun.server.util.regexp.*;RE r = new RE (“a(.*)b”); // strings that begin with ‘a’ and end with ‘b’

© Alexander & Offutt, 1999-2007 94

Regular Expressions Methods

• Regular expression methods can throw “RESyntaxException”• r.setMatchFlags (int)

– MATCH_CASEINDEPENDENT == 1 // ignores case– MATCH_MULTILINE == 2 // ??

• r.match (“aGMUb”)– returns true if the string is a member of the set of strings defined by r

• Splitting strings– RE r = new RE (“:”);– String substrings [ ] = r.split (“swe:cs:ece:ee:syst”);– substrings will now contain 5 strings, “swe”, “cs”, “ece”, “ee”, “syst”

• Replacing substrings– RE r = new RE (“hermes”);– String newStr = r.substr (“http://www.hermes.gmu.edu:8080/offutt/servlet”, “ise”);– newString will now contain “http://www.ise.gmu.edu:8080/offutt/servlet”.

RE r = new RE (“a(.*)b”); // strings that begin with ‘a’ and end with ‘b’

Page 48: An Overview of Java Part III - Classes and Objectsmason.gmu.edu/~jbaldo/432Lec08B-JavaII.pdf · An Overview of Java Part III - Classes and Objects Jeff Offutt Roger Alexander offutt

© Alexander & Offutt, 1999-2007 95

Compiling Java Programs• Get Java JDK compiler from Sun

– http://java.sun.com/j2se/• javac Fraction.java // compiles Fraction.java

– Most command line compilers (Sun’s JDK)– Creates a file called Fraction.class

• java Fraction // Runs main() in Fraction• CLASSPATH:

– Classpath defines where java.class files will be found– When you compile, classes that you inherit from or use must be in the

CLASSPATH– When you execute, the program must be in your CLASSPATH– Win 2K: settings, control panel, system, advanced, Environment variables

C:\j2sdk1.4.1_01\bin;.;

© Alexander & Offutt, 1999-2007 96

Compiling Java Programs – Packages• Java packages encapsulate several classes in one structure• Putting classes into the same package is simple:

– package myPackage; // at the beginning of the class file– Store all classes in myPackage into a package subdirectory called

myPackage• Compile from the parent directory:

– javac myPackage/Fraction.java• Run by using the “dot” notation:

– java myPackage.Fraction // Runs main() in Fraction