Download PPT file

Document related concepts
no text concepts found
Transcript
CIS 5930-04 – Spring 2001
Part 3: Introduction to the Java
Language:
Object-oriented Concepts
http://aspen.csit.fsu.edu/it1spring01/
Instructors: Geoffrey Fox , Bryan Carpenter
Computational Science and Information Technology
Florida State University
Acknowledgements: Nancy McCracken
Syracuse University
[email protected]
1
Java Language Basics
[email protected]
2
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.
[email protected]
3
Obvious differences from C, C++

No low-level pointers or pointer arithmetic.
– Instead have variables and expressions of reference type.

No malloc() or free()—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.
[email protected]
4
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, . . .)
[email protected]
5
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, eg, class or method
definition, and describe intended use.
[email protected]
6
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.
[email protected]
7
Java Keywords

Java reserves the following keywords:
abstract
boolean
break
byte
case
catch
char
class
const


continue
default
do
double
else
extends
final
finally
float
for
goto
if
implement
import
instanceof
int
interface
long
native
new
package
private
protected
public
return
short
throw
throws
transient
try
void
volatile
while
goto is not allowed in Java, but it’s still reserved!
null, true, and false are literals with special meaning.
[email protected]
8
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”.
[email protected]
9
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).
[email protected]
10
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 ;
[email protected]
11
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
[email protected]
12
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.”) ;
[email protected]
13
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.
[email protected]
14
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 preexisting 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.
[email protected]
15
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—not special syntax!
– They illustrate the general syntax of method invocation on an
object.
[email protected]
16
Array Types

As for objects, declaring an array variable is distinct from
creating on the array:
int states[] ;
// variable declaration
states = new int[128] ;
// array creation
and:

Again, these can be combined:
int states[] = new int[128] ;

Alternative (better?) syntax for declaration:
int[] states ;
[email protected]
17
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.

Array length is given by the length instance variable:
int len = states.length ; // assigns len = 128.
[email protected]
18
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() ;
[email protected]
19
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];
graph[1] = new int[7];
...
graph[1][1] = 9;

// Row 0 has length 4
// Row 1 has length 7
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 do:
icon [8] = new char [17] ; // Now ragged!
[email protected]
20
Java Language—Expressions

Most Java expressions are similar to C. 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
[email protected]
21
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
[email protected]
22
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 { . . . }
[email protected]
23
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) ;
[email protected]
24
Control Flow III: The for Loop Construct

In Java, most often use the C++-like variant:
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
}
[email protected]
25
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;
}
[email protected]
26
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.
[email protected]
27
The Java Object Model: Classes,
Instances and Methods
[email protected]
28
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).
[email protected]
Instance
Variables
Methods
29
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.
[email protected]
30
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
[email protected]
31
“outside” the class—parts of Date that programmers writing
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). . .
[email protected]
32
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!") ;
}
}
[email protected]
33
Instance Variables

A very simple class:
public class Complex {
public double real ;
public double imaginary ;
}

Essentially like a C struct. 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 ;
[email protected]
34
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.35
[email protected]
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.
[email protected]
36
Local variables

Formal parameters of methods, and variables declared
inside the bodies methods, are local variables.

These are a third kind of variable in Java: they are
neither instance variables or class variables.
[email protected]
37
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.
[email protected]
38
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 ;
}
[email protected]
39
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
[email protected]
40
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).
[email protected]
41
this as a prefix

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.
[email protected]
42
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.
[email protected]
43
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 explicitlydefined constructor is given!
[email protected]
44
A Better Potato
class Potato {
public Potato(String name) {
this.name = name ;
// Idiomatic use of this
num++ ;
}
public static int getNum() {
return num ;
}
private String name ;
private static int num = 0 ;
// A static method
// Note: now private
// Also private
}
Potato p = new Potato(“one potato”), q = new Potato(“two
potato”) ;
System.out.println(“There
are ” + Potato.getNum() + “ potatoes”)
[email protected]
45
;
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.
[email protected]
46
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 ;
[email protected]
47
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.
[email protected]
48
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.
[email protected]
49
Examples of overload resolution
void foo(long p) {. . .}
void foo(int p) {. . .}
void foo(long p, int q) {. . .}
void foo(int p, long q) {. . .}
// Signature I
// Signature II
// Signature III
// 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!
[email protected]
50
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.
[email protected]
51
Modifiers of Classes

Possible classModifiers are:
– 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.
[email protected]
52
Modifiers of Fields

In the abstract, the declaration format is:
fieldModifiers type variableDeclaratorList ;
where a variableDeclarator has the format:
fieldName [ dimensionStuff ] [ = expression ]

Possible fieldModifiers are:
– public—this field is accessible from any code.
– protected—accessible from code in a subclass (or 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.
[email protected]
53
Modifiers of Methods

In the abstract, recall, the declaration format is:
methodModifiers returnType methodName (parameter list) [throws
exceptionList ] {
declarations and statements
}

Possible methodModifiers are:
–
–
–
–
–
–
–
–
–
public—this method is accessible from any code.
protected—accessible from code in the same package, 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.
[email protected]
54
The Java Object Model: Inheritance
and the Class Hierarchy
[email protected]
55
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.
[email protected]
56
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
the implementation for some of those methods.
[email protected]
57
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.
[email protected]
58
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.
[email protected]
59
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.
[email protected]
60
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.
[email protected]
61
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.
[email protected]
62
Runtime Lookup of Methods
class Shape {
void draw() {. . .}
}
class Circle extends Shape {
void draw() {. . .}
}
class Rectangle extends Shape {
void draw() {. . .}
}
Search up the inheritance
tree until find first
class that defines method.
class Square extends Rectangle {
// No declaration of draw()
}
Square s = new Square() ;
s.draw() ;
[email protected]
63
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.
[email protected]
64
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 void draw() ;
//abstract class
// 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.
[email protected]
65
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 [email protected]
extended.
66
Protected Access

By default 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).
[email protected]
67
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.

Strictly speaking, Object is the root of every inheritance
diagram.
[email protected]
68
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) { . . . }
public int hashcode() { . . . }
// Equality test
// 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.
}
[email protected]
69
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.

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.

Good programming practice minimizes use of narrowing
conversions, but sometimes they are necessary.
[email protected]
70
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.
[email protected]
71
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.
[email protected]
72
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.
[email protected]
73
Using Vector
void drawAll(Vector shapes) {
for(int i = 0 ; i < shapes.size() ; i++)
( (Shape) shapes.get(i) ).draw() ;
conversion
}
Vector bag = new Vector() ;
bag.addElement(new Circle()) ;
conversion
bag.addElement(new Rectangle()) ;
...
drawAll(bag) ;
// Narrowing
// Widening

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 [email protected]
is not an instance of the type in74 the
cast, a run-time ClassCastException occurs.
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.
This index is now called a “key”.
In simple cases you create a HashMap with the noargument 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)
[email protected]
75
Using HashMap
HashMap table = new HashMap() ;
table.put(“red”, “stop”) ;
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
[email protected]
76
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 [email protected]
add a new kind of run-time check.
77
Overloading with Inheritance
void foo(Object p) {. . .}
void foo(Shape p) {. . .}
void foo(Object p, Shape q) {. . .}
void foo(Shape p, Object q) {. . .}
// Signature I
// Signature II
// Signature III
// 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!
[email protected]
78
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.
[email protected]
79
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.
[email protected]
80
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 noargument 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.
[email protected]
81
Superclass Constructor Invocation
class 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) ;
invocation
// superclass constructor
this.radius = radius ;
}
double radius ;
}
[email protected]
82
Exceptions
[email protected]
83
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!
[email protected]
84
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).
[email protected]
85
throw compared with break
try {
...
throw new MyException()
;
...
} catch (MyException e) {
...
}
...
myBlock : {
...
break myBlock ;
...
}
...


Control jumps to start of
matching catch clause
[email protected]
Control jumps to end of
matching block
86
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 {
...
throw new MyException() ;
// throws clause
// 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.
[email protected]
87
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
}
[email protected]
88
Example using java.io
import 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, say
System.err.println(“IO error: ” + e.getMessage()) ;
System.exit(1) ;
}
[email protected]
89
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. . .
[email protected]
90
Part of the Exception Hierarchy
Throwable
Error
Exception
RuntimeException
IOException
...
EOFException
FileNotFoundException
InterruptedIOException


catch(FileNotFoundException e) { . . . } would catch
specific exception whereas
catch(IOException e) { . . . } would catch all
IOexceptions
[email protected]
91
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.
[email protected]
92
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 message in the instance.
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 static void MyMethod() throws MyException {
...
throw new MyException() ;
...
}

Methods e.getMessage() and e.printStackTrace() can
be used on [email protected]
93
Interfaces
[email protected]
94
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 “nonabstract” members—method implementations, instance
variables, etc—and constructors.
[email protected]
95
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.
[email protected]
96
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
...
}
}
[email protected]
97
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.
[email protected]
98
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);
}
}
[email protected]
99
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.
[email protected]
100
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
Red
Blue
Green
Magenta
Yellow
Cyan
AnyColor
they can be implemented using interface types.
[email protected]
101
Interfaces can hold Constant Definitions

Interfaces can hold fields, provided 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.
[email protected]
102
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.
[email protected]
103
Summary

Interfaces play a crucial role in structuring programs that
need to declare multiple sets of behaviors such as
applets and threads.
[email protected]
104
Packages
[email protected]
105
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;
[email protected]
106
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:
File:
mill
wheat.java:
Package mill ;
Public class Wheat { …}
…
[email protected]
Stone.java:
Package mill ;
Public class Stone { …}
…
107
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
agriculture\mill


(UNIX)
(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:
[email protected]
edu.fsu.csit.mpiJava
108
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.
[email protected]
109
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.
[email protected]
110
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.
[email protected]
111
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.
[email protected]
112
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.
[email protected]
113
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).
[email protected]
114
Further information

The Java 2 API specification:
http://java.sun.com/products/jdk/1.2/docs/api
documentation in javadoc format.

The Java Class Libraries, 2nd Edition, Volumes 1 and 2,
plus supplements for the Java 2 platform.
[email protected]
115