Академический Документы
Профессиональный Документы
Культура Документы
Characteristics of object-oriented
programming: how well does Java match
these?
Scoping
Types
Collections and iteration
October 1999 2
The Ideal Object-Oriented
Language
Objects have state and behavior (simulation
metaphor)
Everything is an object, and all actions are
performed by sending messages.
Encapsulation: you interact with an object by
sending messages
Dynamic binding of message to object methods
Inheritance
October 1999 3
Other Issues
October 1999 4
Java: A Timeline
Patrick Naughton, James Gosling, 23-May-1995
et al. found the “Green Team” Public launch of Oak,
within Sun. The language “Oak” renamed “Java”
Oak retargeted to web,
is born, targeting embedded 29-May-1996
WebRunner browser is born
applications 1st JavaOne Conference
1991 1995
1993 1997
23-Jan-1996
Sun ships JDK 1.0
NCSA introduces Mosaic
browser, and the World
Wide Web takes off 18-February-1997
Sun ships JDK 1.1
October 1999 5
Java: The Language
October 1999 7
Java vs. C++
/** Application HelloWorld */
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello World!");
}
}
// Application HelloWorld
#include <iostream.h>
October 1999 9
Brewing Java
object model,
object syntax, dynamic features, package
object types, rich class hierarchy system
exceptions
basic operators,
primitive types,
control structures
Java
October 1999 10
Java’s Hybrid Object Model
Primitive types on stack
May be wrapped or boxed into a real object
Integer anInteger = new Integer(43);
(useful for storing in java.util.*’s collections)
Unboxed primitives very similar to in C++
All object instances live in the heap (not stack)
all object creation is done with new
No “delete” — Java uses garbage collection,
but also provides finalize() method
October 1999 11
Primitive types in Java
boolean
char (16-bit) //unicode
byte (8-bit signed)
short (16-bit signed)
int (32-bit signed) Integer types
long (64-bit signed)
float (32-bit signed)
Floating point types
double (64-bit signed)
October 1999 12
Java’s Class Hierarchy
Object
Container
Byte Long
concrete class
wrapped primitives
final class Panel
abstract class
Applet
October 1999 13
Java Documentation
October 1999 14
HelloWorld Applet
HelloWorldApplet.java
import java.applet.*; import java.awt.*;
% appletviewer HelloWorldApplet.html
Or use a web
browser on the
.html file ...
October 1999 17
More on Methods
October 1999
Note: two different x’s and y’s 19
“Override” vs. “Overload”
Override
replace a superclass’s method with a specialized version
signatures must match
(including return type; C++ permits narrowing of return types, Java does not)
Overload
write several methods for a given class
with the same name
language can disambiguate
based on number or types of arguments
October 1999 20
More on Scoping
October 1999 21
Inner Class Example
// from Arnold & Gosling Java book
October 1999 22
Inner Class Example cont.
October 1999 23
Java’s Class Hierarchy
Object
Container
Byte Long
concrete class
wrapped primitives
final class Panel
abstract class
October 1999
Applet 24
Java variables hold...
primitive
boolean foo; // boolean, not bool as in C++
char aChar = 'a'; // 16 bit char (unicode)
Object reference (may be null)
ColoredBall cball = new ColoredBall(); String literals actually
Ball ball = cball; invoke constructor
e.g., new String("World")
Array reference
int[] intArray = { 1, 2, 3, 4, 5 };
String[] strArray = { "Hello", "World" };
// same as
String[] strArray = new String[2];
strArray[0] = new String("Hello");
strArray[1] = new String("World");
October 1999 25
Arrays
Similar to:
Java arrays are 1st-class Objects
0-indexed
Bounds checking performed
Store/Retrieve using [] operator
strArray[0] = strArray[1];
Have implicit length field
strArray.length 2
A field, not a method!
October 1999 26
Collections
Interface: Collection
classes that implement this interface include
HashSet, HashMap, LinkedList, etc
However … unlike arrays, all you know about the
type of the element in a collection is that it is an
Object. Must do runtime casts if you need more
type information. Annoying.
Another annoyance: must wrap primitive types
to insert them into a collection.
October 1999 27
Iterating through Collections
collections implement the iterator() method, which returns an Iterator.
Need a new class of iterator for each new kind of Collection
October 1999 28
Typing Rules for Arrays
Suppose we have a class Point with a subclass ColoredPoint.
Point has fields x and y. ColoredPoint has an additional color field.
October 1999 29
Typing Rules for Arrays (2)
October 1999 30
Typing Rules for Arrays (3)
October 1999 31
Identifiers
October 1999 32
import statement
Two forms:
import java.util.HashTable;
Just make the HashTable class available from package java.util
import EDU.Washington.grad.gjb.cassowary.*;
Make all classes from package available on demand
October 1999 33
Class Access Protection
package EDU.Washington.grad.gjb.cassowary;
class Helper { … }
October 1999 34
Private: most restrictive
access modifier
ge
ka
ac
e
public class Point {
nt s, nt p
ag
ck
private int x, y;
re
e
pa
ag
iffe
void setXY(int x, int y) {
ck
e
d
s
m
ss
pa
n
fe cla
sa
si
this.x = x; this.y = y;
cla
dif ub
las
n
re
si
me
s
}
bc
n-
s
no
cla
sa
su
protected void move(int x, int y) {
setXY(this.x+x, this.y+y); Y N N N private
}
public int getX() { return x; } Y Y N N package
public int getY() { return y; } Y Y Y N protected
}
Y Y Y Y public
No “friend” keyword
October 1999 36
No Need for
Forward Declarations
Definition
public class Point { Use
private PointColor c;
// setXY(int,int) used below before its definition in the source
protected void move(int x, int y) { setXY(this.x+x, this.y+y); }
void setXY(int x, int y) { this.x = x; this.y = y; }
private int x, y;
} // no trailing semicolon (C++ requires one)
October 1999 37
Final Fields
October 1999 38
Ball and CBall Example
BallExample/Ball.java BallExample/CBall.java
package BallExample;
package BallExample;
public class CBall extends Ball {
public class Ball implements Bounceable {
private int colorSelector;
private int x, y;
public CBall(int x, int y) {
public Ball(int x, int y) {
super(x,y); // chain constructors
this.x=x; this.y = y;
colorSelector = 0; // for black
}
}
public void Bounce() {
public void Bounce() {
System.err.println("Ball bounces");
System.err.println(”CBall bounces");
}
}
static public void ClassFn() {
static public void ClassFn() {
System.err.println("Ball.ClassFn()");
System.err.println(”CBall.ClassFn()");
}
}
}
}
October 1999 39
Inheritance Mechanisms
extends superclass
similar to “: public” in C++
for expressing an “is-a” relation
implements superinterface
similar in use to C++’s multiple inheritance
for expressing an “is-capable-of” or
“knows-how-to” relation
October 1999 40
Java Interfaces
public interface Bounceable { public interface BounceDropable
public void Bounce(); extends Bounceable {
private void BounceNow(); // error public void Drop();
} }
TopLevelWindow
October 1999 46
Final Methods
October 1999 47
Final Classes
October 1999 50
Threads
public class Pendulum extends Applet implements Runnable {
private Thread myThread;
public void start() {
if (myThread == null) {
myThread = new Thread(this,"Pendulum"); set
setthread's
thread'starget target
myThread.start(); totothis
thisPendulum
Pendulum
} class,
class, anduse
and useits its
} run()
run()method
method
public void run() {
while (myThread != null) {
try { myThread.sleep(100); }
catch (InterruptedException e) { /* do nothing */ }
myRepaint();
}
}
Ref: Boone's Java Essentials for
public void stop() { myThread.stop(); myThread = null; } C and C++ Programmers
}October 1999 51
Summary:
What Java Left Out from C++
No stack objects, only heap objects
No destructors, only finalize() method
No pointers, everything is a reference
No delete, garbage collector instead
No const, only final (methods, fields, classes)
No templates, no preprocessor
No operator overloading
No multiple inheritance of classes
No enumerations or typedefs
October 1999 52
Summary:
What Java Put In (vs. C++)
Garbage collector
Object-rooted, rich class hierarchy
Strings, first-class arrays with bounds checking
Package system with import
interface, implements, extends, abstract
finally blocks, static/instance initializers
Secure and portable JavaVM, threads
Dynamic reflection capabilities, inner classes
JavaDoc system
October 1999 53