opennet technologies introduction to the java language and object-oriented concepts

138
java-fall01 1 .opennet Technologies Introduction to the Java Language and Object-oriented Concepts Fall Semester 2001 MW 5:00 pm - 6:20 pm CENTRAL (not Indiana) Time Geoffrey Fox and Bryan Carpenter PTLIU Laboratory for Community Grids Computer Science, Informatics, Physics Indiana University Bloomington IN 47404 [email protected]

Upload: edric

Post on 09-Jan-2016

46 views

Category:

Documents


0 download

DESCRIPTION

.opennet Technologies Introduction to the Java Language and Object-oriented Concepts. Fall Semester 2001 MW 5:00 pm - 6:20 pm CENTRAL (not Indiana) Time Geoffrey Fox and Bryan Carpenter PTLIU Laboratory for Community Grids. Computer Science, Informatics, Physics Indiana University - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: opennet Technologies Introduction to the Java Language and Object-oriented Concepts

java-fall01 1

.opennet TechnologiesIntroduction to the Java Language

and Object-oriented ConceptsFall Semester 2001 MW 5:00 pm - 6:20 pm CENTRAL (not

Indiana) Time

Geoffrey Fox and Bryan Carpenter

PTLIU Laboratory for Community GridsComputer Science,

Informatics, PhysicsIndiana UniversityBloomington IN [email protected]

Page 2: opennet Technologies Introduction to the Java Language and Object-oriented Concepts

java-fall01 2

Overview

Page 3: opennet Technologies Introduction to the Java Language and Object-oriented Concepts

java-fall01 3

What is Java, in a Nutshell? What is Java?

– A simple, object oriented, distributed, interpreted, robust, safe, architecture neutral, portable, high performance, multithreaded, dynamic, programming language.

Java is interesting because– It is both a general purpose object-oriented language

along the lines of C++, and– It is particularly designed to interface with Web pages

(Java on client) and to enable distributed applications over the Internet with Java on Server .

– It has good software engineering properties The Web is becoming the dominant software

development arena; this is driving Java as perhaps the best supported, most widely taught language.– Even outside the Web, e.g. in scientific computing, Java is

as good and in some respects better than other languages.

Page 4: opennet Technologies Introduction to the Java Language and Object-oriented Concepts

java-fall01 4

Architecture of Java (Client) Applications

Java applications are compiled and run on a machine just like any other general programming language such as C/C++. No web server or network are required although Java applications may also use network connections for distributed computing.

One can download dynamically for applets or servlets

There are also native (conventional) Java compilers

Java code

is compiledto produce

byte code

run by JavaVirtual Machine(JVM) to produceresults

Page 5: opennet Technologies Introduction to the Java Language and Object-oriented Concepts

java-fall01 5

Java Applications in a Nutshell Java programs written in a file with extension

“.java”.

Applications are .java files with a main() method. This is called by the Java system.

Compile and run a Java application (using bytecodes):– Run the compiler on a .java file: javac MyProgram.java producing a file of Java byte code,

MyProgram.class

– Run the interpreter on a .class file: java MyProgram which executes the byte code

The tools javac and java are part of JDK.

Page 6: opennet Technologies Introduction to the Java Language and Object-oriented Concepts

java-fall01 6

The Simplest Java Application: Hello,World!

Since Java is object-oriented, programs are organized into modules called classes, which may have data in variables called fields, and subroutines called methods.

class HelloWorld { public static void main (String[] args) { System.out.println(“Hello World!”); }}

Each program is enclosed in a class definition.Each program is enclosed in a class definition.

main() is the first method that is run.main() is the first method that is run.main() is the first method that is run.main() is the first method that is run.

The notation class.method or The notation class.method or package.class.method is how package.class.method is how to refer to a public method to refer to a public method (with some exceptions).(with some exceptions).

Syntax is similar to C - Syntax is similar to C - braces for blocks, semicolon braces for blocks, semicolon after each statement.after each statement.

Page 7: opennet Technologies Introduction to the Java Language and Object-oriented Concepts

java-fall01 7

Java vs. JavaScript

Despite the name, JavaScript is a different language from Java, albeit with some similarities.

A JavaScript program is written directly in the HTML page, and executed by the JavaScript interpreter, so also allows dynamic web page content in the browser window.

JavaScript is special purpose - it is an object-based language that deals directly with browser entities like windows, text fields, forms, frames and documents.

JavaScript can respond to browser events like mouse clicks and user-typed text.

JavaScript is fast to write, but not as powerful as Java.

Page 8: opennet Technologies Introduction to the Java Language and Object-oriented Concepts

java-fall01 8

Multi-tier Architecture Distributed applications on the web naturally have a multi-

tier architecture. Java plays a role at all three levels:

– Graphical User Interface and client side analysis systems, including visualization

– Middle layer servers and software integration, including web servers, distributed object servers and other application servers.

– Less important for back end client software, which may be legacy code.

Middle level servers

Client user interface running through browser

Internet

Internet or proprietary network

Backend computing or databases

Page 9: opennet Technologies Introduction to the Java Language and Object-oriented Concepts

java-fall01 9

History of Java Language and Team

Starts in 1991 as Project Green—semi-autonomous task force in Sun focusing on operating software for consumer electronic devices, e.g. smart set-top boxes.

Gosling (creator of Sun NeWS) considers C++ too complex and initiates development of Oak, later renamed to Java. Similarities to UCSD P-system.

A PDA (Personal Digital Assistant), codename “*7”, based on Oak/Java ready in 1993. Green Team becomes FirstPerson, Inc.

*7 proposal to Time-Warner rejected in 1993. 3DO deal falls through in 1994. FirstPerson, Inc. dissolves.

Small group (~30 people, becomes the Java Team) continues and decides to adapt Oak as a Web technology.

Page 10: opennet Technologies Introduction to the Java Language and Object-oriented Concepts

java-fall01 10

History of Java Language and Team to Dec. 95

Experimental Web browser written in Java, called WebRunner, later renamed HotJava, ready in 1994.

Alpha release of Java and HotJava April '95.

Netscape licenses Java in May '95 and builds Java into Netscape 2.0

Beta Java Development Kit (JDK) and first Java books Summer/Fall '95.

Dec 4, 1995 Business Week cover story: "Software Revolution—The Web Changes Everything" presents Java as a breakthrough force in the expanding Web/Internet.

In next week, SGI, IBM, Adobe, Macromedia and finally Microsoft adopt/license Java. Java is adopted by Web community.

The rest is as they say history …………………..

Page 11: opennet Technologies Introduction to the Java Language and Object-oriented Concepts

java-fall01 11

Java Features—Simple and Familiar

Familiar as it looks like C++, but simpler to program.– omits several confusing features of C++ including

operator overloading, multiple inheritance, pointers and automatic type coercions

Adds automatic garbage collection to make dynamic memory management much easier than in C or C++.– No more frees or deletes. No more memory leaks.

Adds Interface construct, similar to Objective C concept, to compensate for the lack of multiple inheritance.

Small kernel is suitable for Java ports to consumer electronic devices.– But need customization J2ME to be effective (remove

unnecessary features and support special capabilities of PDA’s etc.)

Page 12: opennet Technologies Introduction to the Java Language and Object-oriented Concepts

java-fall01 12

Java Features—Architecture-Neutral

C/C++ programming in a heterogeneous network environment demands compatibility across several vendor platforms and their compilers.

Solved in Java by designing platform-independent binary representation called Java bytecode—comparable to P-code in UCSD Pascal.

Java compiler reads Java source and generates Java bytecode, which is shipped to user.

Each client must have a Java Virtual Machine program, which interprets (“runs”) Java bytecodes.

Page 13: opennet Technologies Introduction to the Java Language and Object-oriented Concepts

java-fall01 13

Java Features—Robust Java enforces compile-time type checking and this

eliminates some error prone constructs of C/C++.

Pointer arithmetic is eliminated which allows for, e.g., runtime checking of array subscripts, and enforces security of the Java model.

Explicit declarations are always required; argument types of methods are always checked (unlike C). This allows the Java complier to perform early error detection.

Java is most secure of popular languages because it is strict and security was built in

Page 14: opennet Technologies Introduction to the Java Language and Object-oriented Concepts

java-fall01 14

The Java 2 Platform

Sun are now offering 3 “editions”:

Java 2 platform, Standard Edition (J2SE)

– Refines earlier JDKs

– Available in version 1.4.

Java 2 platform, Enterprise Edition (J2EE)

– Incorporates multiple technologies for server-side and multi-tier applications.

Java 2 platform, Micro Edition (J2ME)

– Optimized run-time environment for consumer products.

Page 15: opennet Technologies Introduction to the Java Language and Object-oriented Concepts

java-fall01 15

Installing JDK

Become administrator (for Windows) or root (for Linux, etc.) – This is recommended though probably not essential.

Go to http://java.sun.com/j2se/1.4 Select “Download Java 2 SDK, standard edition, v1.4.x,”

for Windows or Linux, etc. Download the software, then read

http://java.sun.com/j2se/1.4/install-windows.html or http://java.sun.com/j2se/1.4/install-linux.html, etc.– Pay attention to instructions for setting PATH.

These give a command line interface for the Java compiler javac and the Java interpreter (JVM driver) java, etc.– If you are familiar with UNIX environments, but want to use

these commands from Windows, consider installing Cygwin: www.cygwin.com.

Page 16: opennet Technologies Introduction to the Java Language and Object-oriented Concepts

java-fall01 16

Java Books—I

Core Java, by Gary Cornell and Cay S. Horstmann, offers detailed coverage of the whole language and packages for advanced programmers, including the Swing Set. (We will not cover these user interface issues here) Also Volume 2 gives good coverage of advanced topics such as JDBC, RMI, JavaBeans and security.

Java, How to Program, by Deitel and Deitel, Prentice-Hall, starts with beginning programming concepts and progresses rapidly through Java language. It has the most programming exercises and also has companion teaching multimedia books. The third edition has Swing Set and also the advanced API’s.

Page 17: opennet Technologies Introduction to the Java Language and Object-oriented Concepts

java-fall01 17

Java Books—II The Java Programming Language, by Ken Arnold and

James Gosling, David Holmes, 3rd Edition, Addison-Wesley, 2000, is the classic on the language basics for intermediate and advanced programmers. It covers threads and I/O packages, but not applets or windowing packages.

Java in a Nutshell, by David Flanagan, is the language reference book in the familiar O'Reilly series. One of the better references. Also Java Examples in a Nutshell.

The Java Language Specification, second edition. James Gosling, Bill Joy, Guy Steele, Gilad Bracha, April 2000. The ultimate reference for hardened computer scientists/compiler writers.

Page 18: opennet Technologies Introduction to the Java Language and Object-oriented Concepts

java-fall01 18

Resources for the Java Programming Language

http://java.sun.com web site has plenty of references including– Tutorial:

http://web2.java.sun.com/docs/books/tutorial

– Books:http://web2.java.sun.com/docs/books

Collection of Java Resources:http://www.gamelan.comhttp://www.jroundup.com/

Page 19: opennet Technologies Introduction to the Java Language and Object-oriented Concepts

java-fall01 19

Java Language Basics

Page 20: opennet Technologies Introduction to the Java Language and Object-oriented Concepts

java-fall01 20

Obvious similarities to C, C++

Java syntax has many similarities to C, C++.

All variables must be declared

Syntax of expressions and control structures almost identical to C, C++

C or C++ style comments allowed.

For Fortran programmers, syntax is a bit different (; to end line { …} to delineate blocks ) for basic material. Fox thinks “structured programming syntax more natural than Fortran 90.

– Arrays not as good for Science as those in Fortran

– No Array syntax as in Fortran90

Page 21: opennet Technologies Introduction to the Java Language and Object-oriented Concepts

java-fall01 21

Obvious differences from C, C++

No low-level pointers or pointer arithmetic.

– Instead have variables and expressions of reference type.

No malloc() or free() to allocate more memory for dynamically created data structures —instead have a “new” operator for creating objects, plus automatic garbage collection.

Can declare variables almost anywhere (like C++).

No struct, union, enum, typedef—classes and objects are used uniformly instead.

Page 22: opennet Technologies Introduction to the Java Language and Object-oriented Concepts

java-fall01 22

Primitive types rationalized

Java characters use 16-bit Unicode Worldwide Character Encoding instead of 8-bit ASCII. Supports all alphabets and languages.

Primitive types for integers and floats have machine independent semantics.

Boolean expressions in Java have value “true” or “false” (not 0, 1, . . .)

Page 23: opennet Technologies Introduction to the Java Language and Object-oriented Concepts

java-fall01 23

Three kinds of comments in Java

/* ignore all between stars */– As for C

// ignore all till the end of this line– As for C++

/** this is a documentation comment */– Should appear immediately before, e.g.,

class or method definition, and describe intended use.

Page 24: opennet Technologies Introduction to the Java Language and Object-oriented Concepts

java-fall01 24

Documentation Comments Used by documentation-generating tools like

javadoc to produce documentation, typically in HTML form.

Optionally include formatting tags like @param, which flags a description of a method parameter:

/** This method does what it feels like. @param bar This is a pointless

argument. */ void foo (int bar) {. . .}

Other formatting tags include @returns which flags a description of a method result value, or @see name, which creates a hypertext link to name.

Page 25: opennet Technologies Introduction to the Java Language and Object-oriented Concepts

java-fall01 25

Java Keywords Java reserves the following keywords:

abstractbooleanbreakbytecasecatchcharclassconst

continuedefaultdodoubleelseextendsfinalfinallyfloat

forgotoifimplementsimportinstanceofintinterfacelong

nativenewpackageprivateprotectedpublicreturnshortthrow

throwstransienttryvoidvolatilewhile

goto is not allowed in Java, but it’s still reserved (to protect Fortran programmers)!

null, true, and false are literals with special meaning.

Page 26: opennet Technologies Introduction to the Java Language and Object-oriented Concepts

java-fall01 26

Java Language—Program Structure

Source code of a Java program consists of one or more compilation units, each implemented as a file with extension “.java”.

Each compilation unit can contain:– a package statement – import statements – class declarations and/or interface declarations.

In typical Java development environments, exactly one of the class (or interface) declarations in each compilation should be marked public.

The file should be named after the public class. e.g. if the public class is Foo, the file name should be “Foo.java”.

Page 27: opennet Technologies Introduction to the Java Language and Object-oriented Concepts

java-fall01 27

Java Types

Each Java variable or expression has a definite type, given by a declaration such as int i; double x, y, z; Color c;

There are two sorts of type:– Primitive types like ints or booleans are

built into the language. – Reference types. These include class types

like Color, and array types (and also interface types).

Page 28: opennet Technologies Introduction to the Java Language and Object-oriented Concepts

java-fall01 28

Primitive Types There are 4 integer types: byte short int long Sizes are 8, 16, 32 and 64 bits, respectively.

float is 32 bits, double is 64 bits. Floating point arithmetic and data formats are defined by IEEE 754 standard.

char format is defined by 16 bit Unicode character set.

boolean is either true or false.

One can use casts for arithmetic conversion, as in: int i ; float x ; i = (int) x ;

Page 29: opennet Technologies Introduction to the Java Language and Object-oriented Concepts

java-fall01 29

Reference Types

These are the types associated with composite entities like objects and arrays.

They are called reference types because a variable or expression in a Java program with reference type represents a reference (or pointer) to a composite entity.– Any variable of reference type may take the

value null. Reference types can be divided into:

– Class types– Interface types (discussed later)– Array types

Page 30: opennet Technologies Introduction to the Java Language and Object-oriented Concepts

java-fall01 30

Strings—an Example of a Class Type

Java environments provide predefined classes for common data types. Every Java environment provides a String class.

Declaration of a String variable looks like: String s ; // variable declaration

The variable declaration itself doesn’t create any objects. We can create a new String object by, e.g.: s = new String(“This is the text”) ; //

object creation

These may be combined on one line: String s = new String (“This is the

text.”) ;

Page 31: opennet Technologies Introduction to the Java Language and Object-oriented Concepts

java-fall01 31

A Constructor Function In the object creation expression:

new String (“This is the text.”) the term

String (“This is the text.”) is a constructor invocation. All classes have special “functions” called constructors.

These functions have the same name as the class. They initialize the fields of the object.

Constructor functions are only used in object creation operations—nearly always directly after a new operator.

In this example the constructor has one argument: a string literal.– We will see later that in general constructors can

have arbitrary argument lists.

Page 32: opennet Technologies Introduction to the Java Language and Object-oriented Concepts

java-fall01 32

Some features of Strings.

Strings are Java objects, but Java provides some syntax peculiar to strings.

In fact literal string in double quotes itself refers to a pre-existing String object—so in practice we may drop new operation for string constants:

String s = “This is the text.” ;

After creation, characters of a string object never change.– In other words: string objects are immutable.

Page 33: opennet Technologies Introduction to the Java Language and Object-oriented Concepts

java-fall01 33

Operations on Strings.

Although a String object is immutable, String-valued variables can be reassigned to refer to new string objects:

String str = “Chicken soup with rice” ; int n = str.indexOf( ‘w’ ) ; str = str.substring(0,n) + “is n” + str.substring(n+6) ; // Result: “Chicken soup is nice”.

The operator + is used for concatenation (special syntax for strings). indexOf() and substring() are methods of the String class— and are

not a special syntax!

– They illustrate the general syntax of method invocation on an object.

Page 34: opennet Technologies Introduction to the Java Language and Object-oriented Concepts

java-fall01 34

Array Types

As for objects, declaring an array variable is distinct from creating on the array: int states[] ; // variable

declaration and:

states = new int[128] ; // array creation

Again, these can be combined: int states[] = new int[128] ;

Alternative (better?) syntax for declaration: int[] states ;

Page 35: opennet Technologies Introduction to the Java Language and Object-oriented Concepts

java-fall01 35

Subscripts With states is declared as above:

int states[] = new int[128] ;

it can be subscripted by integers from 0 to 127.

Subscripts are checked at runtime: states[-1] or states[128] will immediately generate exceptions.

– This subscript checking is an example of where Java trades robustness for performance

Array length is given by the length instance variable: int len = states.length ; // assigns len = 128

One cannot change the length of an Array – the Java vector class is designed for this

Page 36: opennet Technologies Introduction to the Java Language and Object-oriented Concepts

java-fall01 36

Arrays of Objects

Arrays of arbitrary objects can be constructed, e.g.: Color manycolors[] = new

Color[1024]; This creates an array of object references. It

does not create actual objects for individual elements.

Before you use the array elements, you may need to use object constructors to allocate each object, e.g.:

for (int i = 0 ; i < 1024 ; i++) manycolors [i] = new Color() ;

Page 37: opennet Technologies Introduction to the Java Language and Object-oriented Concepts

java-fall01 37

Multidimensional Arrays Multidimensional arrays are arrays of arrays. In general

these arrays may be “ragged”:

int graph[][] = new int[2][]; graph[0] = new int[4]; // Row 0 has length 4 graph[1] = new int[7]; // Row 1 has length 7 . . . graph[1][1] = 9;

Shorthand syntax for creating a rectangular array: char icon[][] = new char [16][16]; // 16 by 16

array

– Note icon is still logically an arrays of arrays, and nothing in Java forces it to stay rectangular. E.g. later someone might doicon [8] = new char [17] ; // Now ragged!

Does not violate rule that Array lengths constant as icon [8] points to a new array of length 17.

Page 38: opennet Technologies Introduction to the Java Language and Object-oriented Concepts

java-fall01 38

Java Language—Expressions

Most Java expressions are similar to C or Fortran. Here are some examples:

– arithmetic:2 + 3(2 + 3) * i

– auto-increment and decrement:i++ // equivalent to i = i +1

– Boolean:((i > 0) && (j > 0)) || (state == –1)

– bit operations:i << 1 // Shift bit pattern 1 place left

– conditional expression:(i > 0) ? expression1 : expression2

False

True

Page 39: opennet Technologies Introduction to the Java Language and Object-oriented Concepts

java-fall01 39

Java Language—More Expressions

Java has some expressions of its own:

– string concatenation:“fred” + “jim” // Value is “fredjim”

– object “instance of” test:(a instanceof B) // true iff object a has

type (class) B

Page 40: opennet Technologies Introduction to the Java Language and Object-oriented Concepts

java-fall01 40

Java Control Flow. I: if Statements

Conditional execution of statements: if (some Boolean expression) { statements to be executed if true }

Optional else clause: if (some Boolean expression) { statements to be executed if true } else { statements to be executed if false }

Nested example: if (some Boolean expression) { . . . } else if (another Boolean expression) { . . . } else { . . . }

Page 41: opennet Technologies Introduction to the Java Language and Object-oriented Concepts

java-fall01 41

Control Flow II: while Loop Constructs

Normal while loop: while (any Boolean) { Stuff to do }

Example: int i = 0 ; while(i < a.length) { a [i] = i * i ; i++ ; }

while loop with test at end: do { What to do } while (another Boolean) ;

Page 42: opennet Technologies Introduction to the Java Language and Object-oriented Concepts

java-fall01 42

Control Flow III: The for Loop Construct

In Java, most often one uses the C++-like variant (cf. DO loops in Fortran): for (declaration1 ; booleanExpression ; expressionList2) { Statements to do }

The declaration declaration1 is effected at start of loop, comma-separated expressionList2 is evaluated after every iteration, and the loop terminates when booleanExpression is false.

Typical example: for (int i = 0 ; i < a.length ; i++) a [i] = i * i ;

The original C-like form (no declaration) also available: for (expressionList1 ; booleanExpression ; expressionList2) { Statements to do }

Page 43: opennet Technologies Introduction to the Java Language and Object-oriented Concepts

java-fall01 43

Control Flow IV: The switch Construct

Identical to C:

switch (expression) { case Constant1: // Do following if expression==Constant1 Bunch of Stuff break; case Constant2: // Do following if expression==Constant2 Bunch of Stuff break; default: // Do the following otherwise Bunch of Stuff break; }

Page 44: opennet Technologies Introduction to the Java Language and Object-oriented Concepts

java-fall01 44

Control Flow V: break and continue

Unlabeled break statement immediately exits the enclosing switch, while, do or for construct: while (true) if (++i == a.length || a[i] == v) break ;

Labeled break statement allows to exit an arbitrary enclosing statement, provided it is labeled: assign: { if (i >= a.length) break assign ; a[i] = v ; }

(This is not the best way to do this!)

The continue statement skips to the end of the current iteration of the enclosing while, do or for.

Page 45: opennet Technologies Introduction to the Java Language and Object-oriented Concepts

java-fall01 45

The Java Object Model: Classes, Instances and

Methods

Page 46: opennet Technologies Introduction to the Java Language and Object-oriented Concepts

java-fall01 46

The Java Object Model Overview Programs are composed of a set of

modules called classes. Each class is a template specifying a set of behaviors involving the data of the class.

Each class has variables, or fields, to hold the data, and methods—akin to functions or procedures in other languages—to define the behaviors.

Each object in a program is created as an instance of a class. Each class instance has its own copy of the instance variables defined for the class.

Classes can be used for data encapsulation, hiding the details of the data representation from the user of the class (e.g., by marking variables as private).

InstanceVariables

Methods

Page 47: opennet Technologies Introduction to the Java Language and Object-oriented Concepts

java-fall01 47

Defining a Class A class declaration consists of:

– a header giving the class name, modifiers, and possible superclass and interface structure.

and a class body usually containing:– declarations of fields (possibly with initializations)—

class variables and instance variables.– declarations of methods.– declarations of constructors. These “functions”

look like methods, but have the same name as the class. They do initialization when objects—class instances—are created.

– nested class and interface definitions.– class or (rarely) instance initialization statements.

Page 48: opennet Technologies Introduction to the Java Language and Object-oriented Concepts

java-fall01 48

Example: a Predefined Class A (small) part of the Java Date class:

public class Date implements Serializable, Cloneable { public Date( ) {. . .} //

Constructor public Date(long msSinceEpoch) {. . .} // Constructor

public int getTime( ) {. . .} // Accessor public void setTime(long msSinceEpoch) {. . .} // Mutator

public boolean after(Date when) {. . .} // Comparision public boolean equals(Object obj) {. . .} // Comparision . . . }

Note: all variables, methods and constructors visible from “outside” the class—parts of Date that programmers writing code in other classes are allowed to use—have the public modifier in their declaration.

Page 49: opennet Technologies Introduction to the Java Language and Object-oriented Concepts

java-fall01 49

Creating a Class Instance The Date class represents a particular date and time,

with a resolution of milliseconds.

The first of the two Date constructors (“no-argument constructor”) constructs an instance of the Date class and sets its value to the current moment: new Date()

Constructors (like methods) can be overloaded. Constructors of same name are distinct if they have distinct argument types. If ms is a long, the object: new Date(ms)

represents a moment ms milliseconds after January 1, 1970, 00:00:00 UTC (Coordinated Universal Time).

Java will become obsolete (2^63 – 1) / 1000 seconds after that (approximately 292 million years AD, UTC). . .

Page 50: opennet Technologies Introduction to the Java Language and Object-oriented Concepts

java-fall01 50

Example of Using a Class An example application using a method of the Date

class:

import java.util.Date;

public class DateTest {

public static void main (String[ ] args) { Date early = new Date(1000) ; // very

early seventies! Date today = new Date() ; // Now! if (today.after(early)) System.out.println( "Today is not

early!") ; } }

Page 51: opennet Technologies Introduction to the Java Language and Object-oriented Concepts

java-fall01 51

Instance Variables A very simple class:

public class Complex { public double real ; public double imaginary ; }

Essentially like a C struct. (i.e. just a collection of variables) Every instance of Complex has its own real and imaginary variables. These fields are therefore called instance variables.

Use: Complex z = new Complex() ; // Default constructor

z.real = 0.0 ; z.imaginary = 1.0 ;

Page 52: opennet Technologies Introduction to the Java Language and Object-oriented Concepts

java-fall01 52

Class Variables Besides instance variables, a class may contain “global

variables” that are not associated with any instance.

A class variable (also called a static variable) is flagged by the static modifier in its declaration:

class Potato { public String name;

static public int num = 0 ; // Class variable—number of

potatoes. }

Potato p = new Potato(), q = new Potato() ;

p.name = “one potato” ; q.name = “two potato” ;

Potato.num += 2 ; // static field prefix is class name.

Page 53: opennet Technologies Introduction to the Java Language and Object-oriented Concepts

java-fall01 53

Method Definitions Subprograms in Java are called methods. In the abstract, the

declaration format is: methodModifiers returnType methodName

(parameter list) { declarations and statements }

The parameter list contains the types and names of all the parameters.

The declarations and statements are the body of the method. Parameter names, and variables declared in the body, are local to it.

Control returns from a method when the body finishes execution or a return statement is executed. return statements may return a result value.

Parameters are passed by value but note the value of an Object reference is a reference and not the Object.

Page 54: opennet Technologies Introduction to the Java Language and Object-oriented Concepts

java-fall01 54

Local variables

Formal parameters of methods, and variables declared inside the bodies of methods, are local variables.

These are a third kind of variable in Java: they are neither instance variables or class variables.

Page 55: opennet Technologies Introduction to the Java Language and Object-oriented Concepts

java-fall01 55

Static and Non-static Methods Like fields, methods come in two varieties, which are

properly called instance methods and class methods.

The terms non-static methods and static methods are also commonly used.

In all Java applications illustrated so far, the main() method had the modifier static—the main method of an application is required to be a static method.

All other examples of methods illustrated so far were instance methods.

Page 56: opennet Technologies Introduction to the Java Language and Object-oriented Concepts

java-fall01 56

Instance Methods Instance methods operate in the context of a particular

class instance (i.e. a particular object). The instance variables of the current object can be

accessed without any prefix:

public class Complex {

// Adds z to the current object public void add(Complex z) { real += z.real ; imaginary += z.imaginary ; }

public double real ; public double imaginary ; }

Page 57: opennet Technologies Introduction to the Java Language and Object-oriented Concepts

java-fall01 57

Invoking an Instance method This example initializes a and b, then increments the value of a

by amount b:

Complex a = new Complex(), b = new Complex() ;

a.real = 0.707 ; a.imaginary = -0.707 ; b.real = -1.0 ; b.imaginary = 0.0 ;

a.add(b) ; // Method invocation

This is why one would like operator overloading to represent last asa = a + b;

Page 58: opennet Technologies Introduction to the Java Language and Object-oriented Concepts

java-fall01 58

this

Within an instance method or constructor the keyword this refers to the current instance.– i.e. the object on which the method was invoked, or

which the constructor is initializing.

Appropriate usage—passing self-reference to some other method: public class Complex {

. . . Definition of add(), etc.

public void addTo(Complex accumulator) {

accumulator.add(this) ; } }

– The invocation a.addTo(b) adds the value of a to b, i.e. it is equivalent to b.add(a).

Page 59: opennet Technologies Introduction to the Java Language and Object-oriented Concepts

java-fall01 59

this as a prefix this refers to current instance

Some programmers will write the this prefix explicitly on every access to an instance variable, e.g.:

public void negate() { this.real = – this.real ; this.imaginary = –

this.imaginary ; }

This is legal, but ugly! One time you must use this as a prefix to an instance

variable is when the field is hidden by declaration of a local variable with the same name.– The only common example is in constructor declarations.

A constructor parameter whose value is used to initialize a field is conventionally given the same name as the field it initializes. See examples later.

Page 60: opennet Technologies Introduction to the Java Language and Object-oriented Concepts

java-fall01 60

Static Methods

A static method does not operate in the context of a particular instance.

Instance variables of the class cannot be accessed inside the body of a static method unless an explicit object prefix is given.

The keyword this cannot be used in the body of a static method.

To invoke a static method it should be prefixed by the name of the class (similar rule to accessing class variables).– This prefix can be omitted if the method is invoked

from another method, etc, defined in the same class.

Page 61: opennet Technologies Introduction to the Java Language and Object-oriented Concepts

java-fall01 61

Constructors Constructors are “functions” (not, strictly

speaking, methods) that have the same name as the class they belong to.

Any number of constructors can be defined for a class, provided they can be distinguished by the number and type of their parameters (overloading).

If no constructors are explicitly defined, the compiler generates a single default constructor with no arguments.

– Note: the default constructor disappears once any explicitly-defined constructor is given!

Page 62: opennet Technologies Introduction to the Java Language and Object-oriented Concepts

java-fall01 62

A Better Potatoclass Potato {

public Potato(String name) { this.name = name ; // Idiomatic use of

this num++ ; }

public static int getNum() { // A static method return num ; }

private String name ; // Note: now private

private static int num = 0 ; // Also private}

Potato p = new Potato(“one potato”), q = new Potato(“two potato”) ;

System.out.println(“There are ” + Potato.getNum() + “ potatoes”) ;

One should add as name private

Public String getName() { // Accessor method

return name;}

Page 63: opennet Technologies Introduction to the Java Language and Object-oriented Concepts

java-fall01 63

Remarks In the constructor, the unqualified symbol name

refers to the local variable declared in the parameter list.– Because this declaration hides the declaration of

name as an instance variable, we must prefix with this to access the latter.

The data fields are now private. This means they can be accessed only from methods within the class, not from other classes.

The method getNum() returns a “global” property of the class—the total number of Potato objects that have been created.– Hence it is natural to declare it as a static method

—it is not associated with any individual instance.

Page 64: opennet Technologies Introduction to the Java Language and Object-oriented Concepts

java-fall01 64

Type Conversions Java allows implicit type conversions in some contexts.

Generally speaking the conversions allowed implicitly (without a cast) are what are called widening conversions.

For primitive types, the widening conversions are from any integer type to any wider integer type, (int to long, etc) or from a float to a double.

Narrowing conversions, by contrast, would include conversion from long to int, or from a floating point type to an integer type.

Narrowing conversions usually have to be specified explicitly with a cast, e.g.

float x ; int i = (int) x ;

Page 65: opennet Technologies Introduction to the Java Language and Object-oriented Concepts

java-fall01 65

Overloading A class can declare several methods with the same name,

providing each declaration has a different number of arguments, or different argument types.– We refer to the combination of the method name and its

list of argument types as the signature of the method.

Example:

class Shape { setColor(Color c) { . . .} setColor(int rgb) { . . .} setColor(int r, int g, int b) { . . .} . . . }

– The method setColor() is overloaded with three different signatures.

Page 66: opennet Technologies Introduction to the Java Language and Object-oriented Concepts

java-fall01 66

Calling an Overloaded Method If the types of the argument expressions in a method

invocation exactly match the types of the parameters in one particular declaration of the method, the compiler naturally chooses to call that particular method implementation.

There is a complication, though: the Java language allows implicit type conversion of method arguments.– The allowed conversions are the widening

conversions. In general overload resolution chooses the most

specific method signature matching the actual arguments.– If there are several applicable signatures, and no

single one is more specific than all the others, a compile time error is flagged.

Page 67: opennet Technologies Introduction to the Java Language and Object-oriented Concepts

java-fall01 67

Examples of overload resolution• void foo(long p) {. . .} // Signature I• void foo(int p) {. . .} // Signature II• void foo(long p, int q) {. . .} // Signature III• void foo(int p, long q) {. . .} // Signature IV

• long l ;• short s ;• int i ;• foo(l) ; // Exact match—use Signature I.• foo(s) ; // Do widening conversion of s to int, and use• // Signature II —unique “most specific” case.• foo(l, s) ; // Uses Signature III —only case applicable by• // widening conversions.• foo(i, i) ; // Compile time error! Signatures III and IV • // are both applicable but neither is more

specific• // than the other!

Page 68: opennet Technologies Introduction to the Java Language and Object-oriented Concepts

java-fall01 68

Header of Class Definition—Details

In the abstract, the definition format is: classModifiers class className

[ extends superclass ][ implements interfaceList ]

{ body of class }

The optional extends and implements clauses will be discussed in detail in later lectures.

Note classmodifiers can be absent – called default mode

Page 69: opennet Technologies Introduction to the Java Language and Object-oriented Concepts

java-fall01 69

Modifiers of Classes Possible classModifiers are:

– default—the class may be used by code in current package.– public—the class may be used freely by code outside the

package.– abstract—the class contains abstract methods without

implementation (abstract classes will have subclasses that define implementation of methods—see later).

– final—this class cannot have a subclass: see later.– strictfp—all intermediate results in all float or double

expressions appearing in the class have strict IEEE 754 exponents.

– private—only allowed for a nested class. Meaning as for other members.

– protected—only allowed for a nested class. Meaning as for other members.

– static—only allowed for a nested class. Meaning analogous to other members.

members of a class are:member classes (see later)fieldsMethods

Nested classes discussed briefly later

Page 70: opennet Technologies Introduction to the Java Language and Object-oriented Concepts

java-fall01 70

Modifiers of Fields I In the abstract, the declaration format is:

– fieldModifiers type variableDeclaratorList ;– where a variableDeclarator has the

format:– fieldName [ dimensionStuff ] [ =

expression ]

Examples are:– Static int fred = 3;– int fred = 3; // Equivalent to– protected int fred = 3;

Note fieldmodifiers can be absent – called default mode

Page 71: opennet Technologies Introduction to the Java Language and Object-oriented Concepts

java-fall01 71

Modifiers of Fields II Possible fieldModifiers are:

– public—this field is accessible from any code.– protected—accessible from code in a subclass (as well

as code in the same package—default accessibility).– private—only accessible from code in the same class.– static—this is a class variable: see earlier.– final—this field cannot be modified after it is initialized.– transient—the value of this field will not be included in

a serialized representation of an instance.– volatile—any cached copy of the field maintained by an

individual thread will be reconciled with the master copy every time the field is accessed.

Page 72: opennet Technologies Introduction to the Java Language and Object-oriented Concepts

java-fall01 72

Modifiers of Methods I In the abstract, recall, the declaration format is:

methodModifiers returnType methodName (parameter list) [throws

exceptionList ] { declarations and statements }

An example is: Public String getName() { // Accessor

methodreturn name;

} Note methodmodifiers can be absent – called default mode

Page 73: opennet Technologies Introduction to the Java Language and Object-oriented Concepts

java-fall01 73

Modifiers of Methods II Possible methodModifiers are:

– public—this method is accessible from any code.– protected—accessible from code in the same package

(default) , or a subclass.– private—only accessible from code in the same class.– abstract—the method has no implementation here—

declaration has a semicolon in place of a body.– static—this is a class method: see earlier.– final—this method cannot be overriden: see later.– synchronized—other synchronized methods are locked

out while this method is executing: see later.– native—the implementation of this method is given in a

platform-dependent language. Declaration has a semicolon in place of a body.

– strictfp—intermediate results in all float or double expressions appearing in the body have strict IEEE 754 exponents.

Synchronized refers to treatment of concurrencyWhich is implemented with threads in JavaAlthough an interesting feature of Java, we willNot need it in this class

Strictfp does not allow default Intel 80 bit internalprecision

Page 74: opennet Technologies Introduction to the Java Language and Object-oriented Concepts

java-fall01 74

The Java Object Model: Inheritance and the Class

Hierarchy

Page 75: opennet Technologies Introduction to the Java Language and Object-oriented Concepts

java-fall01 75

Some Dependencies between Classes

Use– A uses B: the most informal and general relation. A

might, for example, call a method from class B, or have a method with argument type B or return type B.

Containment– A has a B: an important special case of use—class A

has a field of type B.

Inheritance– B is an A: class B has all the properties of class A.

The compiler treats B as a special case of A, and allows an instance of B to be used in any place where an instance of A could appear. In general the class B will extend A with some extra properties of its own.

Page 76: opennet Technologies Introduction to the Java Language and Object-oriented Concepts

java-fall01 76

Inheritance The inheritance relation is (unexpectedly?) powerful; it

is built into all fully object-oriented languages.

In Java, if some class A has been defined, we can subsequently declare a new class, B, and specify that it extends A.

Class A is called the superclass of B. Class B is a subclass of A.

The class B is automatically given (inherits) all the fields and method definitions of A. Further fields and methods can be added that are specific to B.

In particular, for every method signature in class A, class B will have a method with identical signature.

Crucially, though, the class B may define a different implementation for some of those methods.

Page 77: opennet Technologies Introduction to the Java Language and Object-oriented Concepts

java-fall01 77

Trivial use of Inheritance class Shape { void setColor(Color color) {this.color =

color ; } Color color ; int x, y ; // position of center, say }

class Circle extends Shape { void drawCircle() {. . .} double radius ; }

class Rectangle extends Shape { void drawRectangle() {. . .} double height, width ; }

Subclasses automatically inherit color, x, y fields of Shape, and setColor() method.

Page 78: opennet Technologies Introduction to the Java Language and Object-oriented Concepts

java-fall01 78

A Limited Kind of Polymorphism void setAllColors(Shape [] shapes, Color color) { for(int i = 0 ; i < shapes.length ; i++) shapes [i].setColor(color) ; }

Shape [] bag = new Shape [N] ; bag [0] = new Circle() ; bag [1] = new Rectangle() ; . . . setAllColors(bag, Color.red) ; . . .

The function setAllColors works on a collection of shapes, and works correctly independently of whether each shape is actually a Circle or a Rectangle.

Page 79: opennet Technologies Introduction to the Java Language and Object-oriented Concepts

java-fall01 79

Class Hierarchies Class hierarchy diagrams represent inheritance

relations between classes:

Class: Shape

Class:Circle

Class:Rectangle

These diagrams become more complex as subclasses are further extended. But they are always trees, because in Java each subclass has a single superclass.

Page 80: opennet Technologies Introduction to the Java Language and Object-oriented Concepts

java-fall01 80

Inheritance with Overriding class Shape { void draw() {} Color color ; int x, y ; } class Circle extends Shape { void draw() {. . .} double radius ; } class Rectangle extends Shape { void draw() {. . .} double height, width ; }

Subclasses override the definition of draw() in the superclass.

Bodies of methods contain the actual code for drawing a circle or rectangle, respectively.

Page 81: opennet Technologies Introduction to the Java Language and Object-oriented Concepts

java-fall01 81

True Polymorphism void drawAll(Shape [] shapes) { for(int i = 0 ; i < shapes.length ; i+

+) shapes [i].draw() ; }

Shape [] bag = new Shape [N] ; bag [0] = new Circle() ; bag [1] = new Rectangle() ; . . . drawAll(bag) ;

The draw() method invoked is the method defined in the class of the referenced object (Circle or Rectangle).– not the implementation defined in the compile-time

type of the variable, namely Shape. drawAll() correctly draws a mixed bag of shapes whose

details may be unknown when this method is written.

Page 82: opennet Technologies Introduction to the Java Language and Object-oriented Concepts

java-fall01 82

Runtime Lookup of Methods

class Shape { void draw() {. . .} }

Square s = new Square() ;s.draw() ;

class Square extends Rectangle { // No declaration of draw()}

class Rectangle extends Shape { void draw() {. . .}}

class Circle extends Shape { void draw() {. . .}}

Search up the inheritancetree until find firstclass that defines method.

Page 83: opennet Technologies Introduction to the Java Language and Object-oriented Concepts

java-fall01 83

Inherited Methods and Overriding

The method associated with the actual class of the instance is called, even if it invoked from code in the superclass.

Suppose we add a drawInColor() method to Shape: class Shape { void draw() {}

void drawInColor(Color color) { this.color = color ; draw() ; }

Color color ; int x, y ; }

The implementation of drawInColor() is inherited by the subclasses. But when it is invoked on one, their own draw() methods are called! More polymorphism.

Page 84: opennet Technologies Introduction to the Java Language and Object-oriented Concepts

java-fall01 84

Abstract Methods and Classes In our example, the draw() method in the Shape class did

nothing. It may not be necessary to give a implementation of this method in the base class at all, because it may be that it is only ever invoked on instances of subclasses representing concrete shapes (as here).

In this situation, the superclass and unimplemented methods can be declared abstract:

abstract class Shape { //abstract class abstract void draw() ; // abstract

method

Color color ; int x, y ; }

– It is not possible to create instances of abstract classes. One must create a subclass that overrides all abstract methods of the base class, giving implementations.

Page 85: opennet Technologies Introduction to the Java Language and Object-oriented Concepts

java-fall01 85

Final Methods and Classes If a method is declared final, it may not be overridden in

subclasses (opposite extreme to abstract, which must be overridden!)

If we declared draw() in Rectangle to be final, we could never give a more specialized draw() in a subclass:

class Rectangle extends Shape { final void draw() {. . .} // final method double height, width ; }

class Square extends Rectangle { void draw() {. . .} // Compile-time

error!! }

– In places where the compiler can tell that a final method will be called, it can produce optimized code to avoid overheads of “late binding”.

A final class cannot be extended.

Page 86: opennet Technologies Introduction to the Java Language and Object-oriented Concepts

java-fall01 86

Protected Access By default (no modifier) a field or method of a class can

be accessed by any code appearing in the same package.– Packages are discussed later.

The access modifier protected on a field or method means that this member can also be accessed by any subclass of the class in which it is declared.

Note this modifier increases accessibility from the default. . .– . . . because a subclass may be declared outside the

package that contains the superclass.– Least accessible members are private (visible in

declaring class only), followed by default (declaring package only), followed by protected (package and subclasses), followed by public (visible everywhere).

Page 87: opennet Technologies Introduction to the Java Language and Object-oriented Concepts

java-fall01 87

Inner Classes

Java 2 introduced a major addition to the original language definition---"nested types".

A nested class (or interface) is a class/interface that is defined “inside” some other class (or interface).

Nested classes and interfaces are sometimes loosely referred to as "inner classes".

Technically, an inner class is only one of several kinds of nested types in Java 2 (see next slide).

Page 88: opennet Technologies Introduction to the Java Language and Object-oriented Concepts

java-fall01 88

Nested Types

field <----> member class– includes: includes:– static variable <----> static member class– instance variable <----> inner class

local variable <----> local class includes: expression <----> anonymous class Anonymous classes used in way reminiscent of lambda

functions in functional languages, (or "blocks" in Smalltalk) to define pieces of code that are used *very* locally– typically in the context of a single expression.– Popular for defining simple event-handlers in GUI

programming, though many other applications as well.

Page 89: opennet Technologies Introduction to the Java Language and Object-oriented Concepts

java-fall01 89

Critique of Nested Types

Nested types are undoubtedly a powerful and useful addition to the language.– Most useful nested types arguably static member

classes (for software engineering) and anonymous classes (for slick "one-liners").

But the introduction of the whole paraphernalia of nested types has significantly complicated the Java language definition.– Many places where, for example, choice between

inherited and enclosing class behaviors could be ambiguous--needs complicated rules to disambiguate.

– JVM definition was frozen before Java 2 introduced nested types, so compilers must preprocess nested types to equivalent outer types--ugly hack.

Page 90: opennet Technologies Introduction to the Java Language and Object-oriented Concepts

java-fall01 90

The Universal Superclass—Object

The Java language provides a superclass for all other classes. If no extends clause is given in a class definition, the class implicitly extends Object.

Array types are also considered to extend Object.

A variable of type Object can hold a reference to any object or array.– This is useful for generic capabilities which apply to

all Object classes

Strictly speaking, Object is the root of every inheritance diagram.

Page 91: opennet Technologies Introduction to the Java Language and Object-oriented Concepts

java-fall01 91

Methods on the Object class

Public class Object {

public final Class getClass() { . . . } // Basis for reflection.

public String toString() { . . . } //A String representation

public boolean equals(Object obj) { . . . } // Equality test

public int hashcode() { . . . } // For use by hash tables

protected Object clone() throws . . . { . . . } // Bit by bit copy

public final void wait() throws . . . { . . . } // Deschedule this thread public final void wait(long millis) throws . . . { . . . } public final void wait(long millis, int nanos) throws . . . { . . . }

public final void notify() throws . . . { . . . } // Reschedule any . . . public final void notifyAll() throws . . . { . . . } // . . . or all threads.

protected void finalize() throws . . . { . . . } // invoked by GC.}

Reflection is a powerful capability to allows you to find out about an Object at run-timetoString labels a classequals test if Objects are identical which includes the case if two objects are identical references

Page 92: opennet Technologies Introduction to the Java Language and Object-oriented Concepts

java-fall01 92

Reference Conversions Conceptually, we saw, an instance of a subclass “is an”

instance of the superclass. Hence one can assign a reference to a subclass object

to a variable of a superclass type.

– Shape fred; Circle jim; fred = jim; //allowed Concretely, this implies a conversion from a subclass

type to a superclass type is regarded as a kind of widening conversion.– Recall widening conversions are allowed implicitly in various

contexts.

Narrowing conversions on reference types go the other way—from a superclass down to some subclass.– Narrowing conversions require an explicit cast.– jim = (Circle) fred;

Good programming practice minimizes use of narrowing conversions, but sometimes they are necessary.

Page 93: opennet Technologies Introduction to the Java Language and Object-oriented Concepts

java-fall01 93

An Aside on Coding Conventions http://java.sun.com/docs/codeconv/html/CodeConvTOC.doc.ht

ml is a good set of “best practice” conventions

Code conventions are important to programmers for a number of reasons:

80% of the lifetime cost of a piece of software goes to maintenance.

Hardly any software is maintained for its whole life by the original author.

Code conventions improve the readability of the software, allowing engineers to understand new code more quickly and thoroughly.

If you ship your source code as a product, you need to make sure it is as well packaged and clean as any other product you create.

There are another set at http://g.oswego.edu/dl/html/javaCodingStd.html

Bryan’s favorite Rule: Do not require 100% conformance to rules of thumb such as the ones listed above

Page 94: opennet Technologies Introduction to the Java Language and Object-oriented Concepts

java-fall01 94

Simple Collections

The package java.util contains a family of collection classes.

Here we will only mention two of the most widely used:– Vector, and– Hashmap.

Note Vector is supposed eventually to be superceded by ArrayList.– Consider using ArrayList in your future

programs, but Vector is so widespread we describe it here.

Page 95: opennet Technologies Introduction to the Java Language and Object-oriented Concepts

java-fall01 95

A Vector is Like an Array A Vector can be used essentially like an ordinary

array. It has a well-defined current size, returned by the

size() inquiry. This can be set with setSize(), but usually a Vector is

grown dynamically using methods on next slide. Vector stores all elements as if the have type Object If 0 < idx < size(), the methods:

void set(int idx, Object obj) Object get(int idx)

respectively assign and retrieve value of element idx.

Page 96: opennet Technologies Introduction to the Java Language and Object-oriented Concepts

java-fall01 96

A Vector can Grow and Shrink Typically one grows a vector by adding a new

element at the end with: void addElement(Object obj)

Causes size() to be incremented by 1. An arbitrary element can be removed by

Object remove(int idx) This method causes higher elements to be shifted

down one place, and size() to be decremented by 1. An element can be inserted in an arbitrary place by

insertElementAt(Object obj, int idx) Element at idx and higher are shifted up one

place, and size() is incremented by 1.

Page 97: opennet Technologies Introduction to the Java Language and Object-oriented Concepts

java-fall01 97

Using Vector void drawAll(Vector shapes) { for(int i = 0 ; i < shapes.size() ; i++) ( (Shape) shapes.get(i) ).draw() ; //

Narrowing conversion }

Vector bag = new Vector() ; bag.addElement(new Circle()) ; // Widening

conversion bag.addElement(new Rectangle()) ; . . . drawAll(bag) ;

For polymorphism, Vector stores items in Object references. Hence, get() returns an Object, which usually needs to be cast back to a more specific type.

If the referenced object is not an instance of the type in the cast, a run-time ClassCastException occurs.

Page 98: opennet Technologies Introduction to the Java Language and Object-oriented Concepts

java-fall01 98

A HashMap is an Associative Array

For future reference, we also discuss HashMap here A HashMap is similar to a vector, but the “index” is an

arbitrary object—very commonly a string.– Perl has excellent support of this using {} syntax

This index is now called a “key”. In simple cases you create a HashMap with the no-

argument constructor, then put key-value pairs in it using Object put(Object key, Object obj)

(returns old value if key was already in the table). Retrieve the element currently indexed by key by:

Object get(Object key) Remove the element currently indexed by key by:

Object remove(Object key)

Page 99: opennet Technologies Introduction to the Java Language and Object-oriented Concepts

java-fall01 99

Using HashMap

HashMap table = new HashMap() ; // Create

table.put(“red”, “stop”) ; // Insert hashes table.put(“green”, “go”) ;

String s = (String) table.get(“red”) ; // returns “stop” String t = (String) table.remove(“green”) ; // returns “go” String u = (String) table.get(“green”) ; // returns null

Page 100: opennet Technologies Introduction to the Java Language and Object-oriented Concepts

java-fall01 100

Widening Conversions on Arrays There is a widening conversion between two array types if

there is a widening reference conversion between their component types.

This is useful, but can lead to anomalies if used carelessly:Circle [] bag = new Circle [N] ;setAll(bag) ; // Widening: Circle [] to Shape

[]. // OK at compile-time.

void setAll(Shape [] shapes) { shapes [0] = new Circle() ; shapes [1] = new Rectangle() ; // Widening: Rectangle to

Shape. // But throws

ArrayStoreException . . . // if invoked as above!}

Effect would be to assign Rectangle to array of Circles. Requires the compiler to add a new kind of run-time check.

Page 101: opennet Technologies Introduction to the Java Language and Object-oriented Concepts

java-fall01 101

Overloading with Inheritancevoid foo(Object p) {. . .} // Signature Ivoid foo(Shape p) {. . .} // Signature IIvoid foo(Object p, Shape q) {. . .} // Signature IIIvoid foo(Shape p, Object q) {. . .} // Signature IV

Object o ;Shape s ;Circle c ;

foo(o) ; // Exact match—use Signature I.

foo(c) ; // Do widening conversion of c to Shape, and use

// Signature II—unique “most specific” case.

foo(o, c) ; // Uses Signature III—only case applicable by // widening conversions.

foo(s, s) ; // Compile time error! Signatures III and IV // are both applicable but neither is more

specific // than the other!

Page 102: opennet Technologies Introduction to the Java Language and Object-oriented Concepts

java-fall01 102

Overload Resolution across Classes

class Shape { void foo(Circle q) {. . .} // Signature I } class Circle extends Shape { void foo(Shape q) {. . .} // Signature II }

Shape s ; Circle c ;

s.foo(c) ; // Uses Signature I—exact match.

c.foo(c) ; // Compile time error! Signatures I and II

// are both applicable but neither is more specific

// than the other! In compile-time overload resolution (choice of

signature), the prefix object expression is treated on the same footing as an extra argument.

Page 103: opennet Technologies Introduction to the Java Language and Object-oriented Concepts

java-fall01 103

Summary: Overloading vs. Overriding Resolution of overloading occurs at compile

time. The compiler chooses a unique method signature out of several different signatures available (or flags a compile time error if it cannot).

Overriding occurs in the context of a single signature. In general, if the class hierarchy contains several definitions with identical method signatures, the appropriate definition is chosen at run time.

Within the body of a class that overrides a method, the method from the superclass can be invoked instead by using the super prefix.

Page 104: opennet Technologies Introduction to the Java Language and Object-oriented Concepts

java-fall01 104

Constructors and Inheritance

Constructors of subclasses must invoke a constructor of their superclass, to initialize the fields there.

If a superclass constructor is not explicitly invoked, the no-argument constructor of the superclass is called, implicitly, by the compiler.

– A compile-time error is flagged if no such constructor exists.

If any superclass constructor other than the no-argument constructor is required, it must be invoked explicitly.

In this case the first statement of a subclass constructor is an explicit constructor invocation using the name super.

Page 105: opennet Technologies Introduction to the Java Language and Object-oriented Concepts

java-fall01 105

Superclass Constructor Invocationclass Shape {

public Shape(Color color, int x, int y) { this.color = color this.x = x ; this.y = y ; } Color color ; int x, y ; }

class Circle extends Shape {

public Circle(Color color, int x, int y, double radius) {

super(color, x, y) ; // superclass constructor invocation

this.radius = radius ; } double radius ;}

Page 106: opennet Technologies Introduction to the Java Language and Object-oriented Concepts

java-fall01 106

Exceptions

Page 107: opennet Technologies Introduction to the Java Language and Object-oriented Concepts

java-fall01 107

Exceptions are Pervasive

Java has a concept of exceptions similar to C++. Unlike C++, Java exceptions are strictly

checked. Most classes in the standard Java library throw

some exceptions. We will see, these must be caught or thrown.

This means that it is almost impossible to write useful Java code without some knowledge of the exception mechanism!

Page 108: opennet Technologies Introduction to the Java Language and Object-oriented Concepts

java-fall01 108

Exception Objects, and throw

Any kind of exception that can be thrown by Java code is described by an exception object. It’s class must be a subclass of Throwable.

If e is a Throwable object, the statement throw e ;

behaves something like a break statement; it causes the enclosing block of code to end abruptly.

If the throw statement appears inside a try statement who’s catch clause matches the class of e, control is passed to the catch clause.

Otherwise the whole method (or constructor) ends abruptly. The exception e is thrown again at the point of invocation (in the calling code).

Page 109: opennet Technologies Introduction to the Java Language and Object-oriented Concepts

java-fall01 109

throw compared with break

try { . . . throw new

MyException() ; . . .} catch (MyException e)

{ . . .}. . .

Control jumps to start of matching catch clause

myBlock : { . . . break myBlock ; . . . } . . .

Control jumps to end of matching block

Page 110: opennet Technologies Introduction to the Java Language and Object-oriented Concepts

java-fall01 110

Methods that throw exceptions

In general, any exception that might be thrown in the body of a method or constructor, in a place where it is not enclosed by a matching try-catch construct, must be declared in a throws clause in the header of the method:

void foo() throws MyException { // throws clause . . . throw new MyException() ; // No enclosing // try-

catch(MyException . . .) . . . }

The compiler will insist invocations of foo() are treated with the same care as actual throw statements—either enclosed in matching try-catch constructs, or declared in turn in the header of the calling method.

Page 111: opennet Technologies Introduction to the Java Language and Object-oriented Concepts

java-fall01 111

Exception Handling in Nested Calls

void method1() { try { method2() ; } catch (Exception3 e) { doErrorProcessing(e); }}

void method2() throws Exception3 { method3() ; // method2 just passes exception

through}

void method3 throws Exception3 { throw new Exception3() ; // create exception}

Page 112: opennet Technologies Introduction to the Java Language and Object-oriented Concepts

java-fall01 112

Example using java.ioimport java.io.* ;

PrintWriter out ; try { out = new PrintWriter(new

FileOutputString(“filename”)) ; // create

and open file out.write(“stuff put out”) ; . . . out.close() ;

} catch (IOException e) { // Catches all I/O errors, including read and write stuff,

System.err.println(“IO error: ” + e.getMessage()) ; System.exit(1) ;}

Page 113: opennet Technologies Introduction to the Java Language and Object-oriented Concepts

java-fall01 113

How (not) to Ignore an Exception Sometimes you can’t think of a good way to recover

from an exception—e.g. an exception thrown by a library method. But the compiler forces you to do something.

Probably the worst thing you can do is to wrap the method invocation in a try-catch with an empty catch clause—– the useless try-catch constructs make the code unreadable, and

– meanwhile, ignoring an error condition and silently carrying on the program may produce code even less reliable than, say, a typical C program, where the library error probably at least aborts the whole program!

Usually it is safer to have your methods throw the exceptions—all the way up to the main method, if necessary. Then at least the program will stop.

If you are really lazy you can just declare every method you ever write with throws Exception. . .

Page 114: opennet Technologies Introduction to the Java Language and Object-oriented Concepts

java-fall01 114

Part of the Exception Hierarchy

catch(FileNotFoundException e) { . . . } would catch specific exception whereas

catch(IOException e) { . . . } would catch all IOexceptions

Throwable

...

Error Exception

RuntimeException IOException

EOFException

FileNotFoundException

InterruptedIOException

Page 115: opennet Technologies Introduction to the Java Language and Object-oriented Concepts

java-fall01 115

Unchecked Exceptions

There are two exceptions (!) to the rule that all exceptions must be explicitly caught or thrown.

Error classes usually represent problems that might occur unpredictably in the JVM. For example OutOfMemoryError (although unusual in practice) might occur at almost any time.

RuntimeException classes usually represent errors “built into” the language—not thrown by a throw statement. There are about 20, including:– ArithmeticException,

ArrayIndexOutOfBoundsException, NullPointerException, ClassCastException, etc.

Note that exceptions that are thrown but not caught appear as error message on stderr. For applets they appear in the “Java console” of the browser.

Page 116: opennet Technologies Introduction to the Java Language and Object-oriented Concepts

java-fall01 116

Defining you own Exceptions The Exception class has fields and methods to give information

how the exception occurred. There are two constructors; one includes a custom message

Can throw an exception of type Exception with a unique message, or create a subclass:class MyException extends Exception { public MyException () { super ("This is my exception message.") ; } public MyException (String gripe) { super (gripe); }}public static void MyMethod() throws MyException { . . . throw new MyException() ; . . . }

Methods e.getMessage() and e.printStackTrace() can be used on exceptions.

Page 117: opennet Technologies Introduction to the Java Language and Object-oriented Concepts

java-fall01 117

Interfaces

Page 118: opennet Technologies Introduction to the Java Language and Object-oriented Concepts

java-fall01 118

Abstract Classes Revisited

Recall an abstract class is a class that contains some abstract method declarations, with no implementation.

An abstract class can only be instantiated indirectly, as a superclass of a class that overrides all the abstract methods, and gives them an implementation. You cannot directly create an instance of an abstract class.– Constructors, static methods, private methods cannot be

abstract.– A subclass that does not override all abstract methods is still

abstract.– A method that overrides a superclass method cannot be

abstract

But an abstract class will generally also contain “non-abstract” members—method implementations, instance variables, etc—and constructors.

Page 119: opennet Technologies Introduction to the Java Language and Object-oriented Concepts

java-fall01 119

Interfaces

An interface is something like an abstract class where every method is required to be abstract.

An interface specifies a collection of instance methods (behaviors) without giving the implementation of their bodies— akin to giving an API: public interface Storable { public abstract void store(Stream s) ; public abstract void retrieve(Stream s) ; }

Interfaces cannot include instance variables, constructors, or static methods.

They can include class variables, but only if they are declared final—essentially constant definitions.

Page 120: opennet Technologies Introduction to the Java Language and Object-oriented Concepts

java-fall01 120

Implementing an interface As for an abstract class, one cannot directly

create an instance of an interface. Unlike an abstract class, one cannot even extend

an interface to create a class. An interface is not a class, and it cannot have subclasses.

Instead, a class must implement an interface:

public class Picture implements Storable { public void store(Stream s) { // JPEG compress image before storing . . . } public void retrieve(Stream s) { // JPEG decompress image after retrieving . . . } }

Page 121: opennet Technologies Introduction to the Java Language and Object-oriented Concepts

java-fall01 121

An Interface is a Contract

Any class that implements an interface is guaranteeing a set of behaviors. The body of the class will give concrete bodies to the methods in the interface.– If any methods in the interface are not implemented, the

class must be declared abstract.

Example: a class that defines the behaviour of a new thread must implement the Runnable interface: public interface Runnable { public void run() ; }

Any interface defines a type, similar to a class type. An instance of any class that implements a particular interface can be assigned to a variable with the associated interface type.

Page 122: opennet Technologies Introduction to the Java Language and Object-oriented Concepts

java-fall01 122

An Interface Defines a Type Assume the classes Picture and StudentRecord

both implement the Storable interface:

public class StudentBody { Stream s; . . . public void register(Picture id_photo, StudentRecord

id_card) { save(id_photo); save(id_card); } public void save(Storable o) { // o has type Storable o.store(s); // as Storable must have method store } }

Widening Conversion

Page 123: opennet Technologies Introduction to the Java Language and Object-oriented Concepts

java-fall01 123

Classes can Implement Several Interfaces

Interfaces address some of the same requirements as multiple inheritance in C++ (for example), but avoid various complexities and ambiguities that come from inheriting implementations and instance variables from multiple superclasses.

A class can extend its superclass and implement several interfaces: class Picture implements Storable, Paintable {

// Body must now include any methods in Paintable,

// as well as store() and retrieve().

. . . }

Instances of the class acquire all the implemented interface types, in addition to inheriting their superclass type.

Page 124: opennet Technologies Introduction to the Java Language and Object-oriented Concepts

java-fall01 124

Interfaces can Extend other Interfaces An interface can extend one or more other interfaces:

interface Material extends Storable, Paintable { // Additional methods if necessary. . . . . . }

If non-trivial “lattices” of types are really needed, eg:

NoColor

GreenBlueRed

AnyColor

CyanYellowMagenta

they can be implemented using interface types.

e.g. Magenta extends Red but implements cyan

Page 125: opennet Technologies Introduction to the Java Language and Object-oriented Concepts

java-fall01 125

Interfaces can hold Constant Definitions

Interfaces can hold fields, provided they are static and final.

An interface can be a natural place to define a collection of related constants, perhaps simulating a C-like enumeration type: public interface Direction { public final static int NORTH = 0 ; public final static int EAST = 1 ; public final static int SOUTH = 2 ; public final static int WEST = 4 ; }

Use constants by, eg, Direction.NORTH. Sometimes a class will implement such an

interface, just so it can access the included constants without using the Direction prefix.

Page 126: opennet Technologies Introduction to the Java Language and Object-oriented Concepts

java-fall01 126

Interfaces can be used as Markers

The Java environment includes several examples of empty interfaces that are used only as markers.

By implementing such an interface, the programmer is typically telling the compiler or runtime system to treat the class in some special way:– Cloneable—the Object.clone() method will throw an

exception if invoked on an object from a subclass that does not implement the empty Cloneable interface.

– Serializable—the ObjectOutputStream.writeObject() method will not write an object that does not implement the empty Serializable interface.

– Remote—any class whose methods may be invoked remotely using the RMI mechanism, must implement the empty Remote interface.

Page 127: opennet Technologies Introduction to the Java Language and Object-oriented Concepts

java-fall01 127

Summary Interfaces play a crucial role in structuring

programs that need to declare multiple sets of behaviors such as applets and threads.

Page 128: opennet Technologies Introduction to the Java Language and Object-oriented Concepts

java-fall01 128

Packages

Page 129: opennet Technologies Introduction to the Java Language and Object-oriented Concepts

java-fall01 129

Packages

One file can contain several related classes, but only one of them can be public. If the public class is called Wheat, then the file must be called Wheat.java.

A set of classes in different files can be grouped together in a package. Each file must start with a package declaration, eg:

package mill;

Page 130: opennet Technologies Introduction to the Java Language and Object-oriented Concepts

java-fall01 130

Packages and Directory Structure (JDK)

In JDK, each of the files in one package must be in the same directory (which may be in an jar archive file).

For simple package names, the name of the directory should be the same as the package:

Directory name: mill

File: wheat.java: Stone.java:Package mill ;

Public class Wheat { …}…

Package mill ;Public class Stone { …}…

Page 131: opennet Technologies Introduction to the Java Language and Object-oriented Concepts

java-fall01 131

Hierarchical Package Names Packages can be grouped hierarchically. For

example, the mill package could be nested in a package called agriculture. Then the name of the package would be changed to agriculture.mill (full name required).

In JDK, the classes of agriculture.mill should appear in a directory called: agriculture/mill (UNIX) agriculture\mill (Windows)

(relative to some directory, which must appear on the user’s CLASSPATH).

Standard Java libraries are in packages with names like java.lang, java.util, java.io, etc.

If you need to construct a globally unique name, can use your Internet domain name, inverted, as a prefix, eg: edu.fsu.csit.mpiJava

Page 132: opennet Technologies Introduction to the Java Language and Object-oriented Concepts

java-fall01 132

Fully Qualified Class Names

A class can always be referred to in Java code by its fully qualified name which includes the package name as a prefix, eg: public class VectorTest { public static void main (String [] args) { java.util.Vector bag = new

java.util.Vector() ; bag.addElement(new

java.lang.String(“item”)) ; }

Using fully qualified names is tedious in general.

Page 133: opennet Technologies Introduction to the Java Language and Object-oriented Concepts

java-fall01 133

Import statements The import declaration allows you to avoid giving

fully qualified names, eg: import java.util.Vector ; // import declaration

public class VectorTest { public static void main (String [] args) { Vector bag = new Vector() ; bag.addElement(new String(“item”)) ; }

Can also import all classes in, eg, java.util by import java.util.* ;

(but note wildcard can only appear in last position).

Note classes (like String) in java.lang are automatically imported.

Page 134: opennet Technologies Introduction to the Java Language and Object-oriented Concepts

java-fall01 134

CLASSPATH The import declaration only controls

conventions on naming within a source file. It doesn’t address basic accessibility of the class files. You can use a class without importing it.

In JDK (except for classes provided with the Java language) jar files or root directories of any package used (or class files for any classes not in any package) must be in the current directory, or in a directory in the CLASSPATH environment variable.

This variable is used by both the compiler javac and the JVM command, java.

Page 135: opennet Technologies Introduction to the Java Language and Object-oriented Concepts

java-fall01 135

Java System Packages, I

java.lang contains essential Java classes and is by default imported into every Java file. So import java.lang.* is unnecessary. For example Thread, Math, Object and wrapper classes are here.

java.io contains classes to do I/O. java.util contains various utility classes that didn't

make it to java.lang. Date is here as are Vector, hashtables, etc.

java.net contains classes to do network applications. Sockets, Internet addresses, URLs etc.

java.applet has the classes needed to support applets java.awt has the original classes to support

windowing—The Abstract Windows Toolkit. java.awt.image has image processing classes.

Page 136: opennet Technologies Introduction to the Java Language and Object-oriented Concepts

java-fall01 136

Java System Packages, II java.awt.datatransfer contains classes to transfer data from a

Java program to the system clipboard (drag-and-drop). java.beans contains classes to write reusable software

components. java.lang.reflect enables a program to discover the accessible

variables and methods of a class at run-time. java.rmi—classes for Remote Method Invocation. java.security enables a Java program to encrypt data and control

the access privileges provided. java.sql—Java Database Connectivity (JDBC) enables Java

programs to interact with a database using the SQL language. java.text are classes that provide internationalization capabilities

for numbers, dates, characters and strings. java.util.jar combines java .class files and other files into one

compressed file called a Java archive (JAR) file.

Page 137: opennet Technologies Introduction to the Java Language and Object-oriented Concepts

java-fall01 137

Additional Java 1.2 System Packages

javax.accessibility—contracts between user interface components and assistive technology.

javax.swing—additional user interface components as well as providing standard “look and feel” for old ones.– border, colorchooser, event, filechooser, plaf,

table, text, tree, undo org.omg.CORBA—Provides the mapping of the

Object Management Group CORBA APIs to the Java programming language, including the class ORB, which is implemented so that a programmer can use it as a fully-functional Object Request Broker (ORB).

Page 138: opennet Technologies Introduction to the Java Language and Object-oriented Concepts

java-fall01 138

Further information

The Java 2 API specification:

http://java.sun.com/products/j2se/1.4/docs/api

documentation in javadoc format.

The Java Class Libraries, 2nd Edition, Volumes 1 and 2, plus supplements for the Java 2 platform.