Day 2 Summary

Back Up Next

 

Java Architecture in Depth

Java the Language
Disclaimer: This IAP course does not cover everything in nearly enough depth - for a good read and complete understanding of Java, read something such as The Java Programming Language.
Java Keywords
	abstract	double		int		super
	boolean		else		interface	switch
	break		extends		long		synchronized
	byte		final		native		this
	case		finally		new		throw
	catch		float		package		throws
	char		for		private		transient
	class		goto		protected	try
	const		if		public		void
	continue	implements	return		volatile
	default		import		short		while
	do		instanceof	static
Java Operators
	postfix operators	[ ] . (params) expr++ expr--
	unary operators		++expr --expr +expr -expr ~ !
	creation or cast	new (type)expr
	multiplicative		* / %
	additive		+ -
	shift			<< >> >>>
	relational		< > >= <= instanceof
	equality		== !=
	bitwise AND		&
	bitwise exclusive XOR	^
	bitwise inclusive OR	|
	logical AND		&&
	logical OR		||
	conditional		? :
	assignment		= += -= *= /= %= >>= <<= >>>= &= ^= |=
java.lang
Primitive Data Types
boolean either true of false (unlike C/C++)
char 16 bit Unicode character
byte 8 bit signed integer
short 16 bit signed integer
int 32 bit signed integer
long 64 bit signed integer
float 32 bit IEEE real number
double 64 bit IEEE real number
Note the class-equiv (Character, Integer, Long, Float, Double) and short/byte promoted to int for calc.
Classes,  Fields, and Methods
Classes are the heart of Java
All classes ultimately derive from java.lang.Object
Fields belong inside a class and can be either instance or class fields
Methods belong inside a class and can be either instance or class methods
myClass.java
class myClass {
	String name;

	myClass(String classname) {
		name = classname;
	}

	public String getName() {
		return name;
	}
}
Objects
Your basic Object
public String toString()
public boolean equals(Object o)
public int hashCode()
protected Object clone() throws CloneNotSupportedException
Examples of Objects
//
//valid object expression statements
//
Object o;
String s = "Welcome to the party!";
myClass cls = new myClass(s);
Hashtable stuff = new Hashtable();
double weights[] = new double[30];
char chessboard[][] = new char[8][8];
stuff.put("A", cls);
cls = (myClass)stuff.get("A");
cls.getName().equals(s);
Objects are references instead of pointers
Use the new operator to create objects
You don't delete objects - garbage collection does it for you automatically
Arrays are special, non-inheritable Objects
Visibility
  Any Package Children Self
public X X X X
protected   same-package X X
package-visible   X X X
private       X
A.java
public class A {
	private String mine = "A";
	protected String family = "protected-A";
	public String world = "public-A";
}

class B extends A {
	public B() {
		System.out.println(mine);	//illegal
		System.out.println(family);	//legal
		System.out.println(world);	//legal
	}
}

class C {
	public C() {
		B b = new B();
		System.out.println(b.mine);	//illegal
		System.out.println(b.family);	//illegal
		System.out.println(b.world);	//legal
	}

	public static void main(String[] args) {
		C c = new C();
	}
}
General Types of Classes
top-level
inner(nested) classes
anonymous - class without a name associated inside another class
named - class with a name associated inside another class
static - class with a name associated with container class
TopLevelClass.java
import java.awt.Frame;
import java.awt.Window;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

public class TopLevelClass extends Frame {	//Top Level Class
	public static class AppListener extends WindowAdapter {	//Static Inner Class
		public void windowClosing(WindowEvent e) {
			((Window)e.getSource()).dispose();
			System.out.println("StaticInnerClass");
		}

		public void windowClosed(WindowEvent e) {
			System.exit(0);
		}
	}

	public TopLevelClass() {
		System.out.println("TopLevelClass");

		class PrivateDataType {	//Named Inner Class
			public PrivateDataType() {
				System.out.println("NamedInnerClass");
			}
		};

		PrivateDataType test = new PrivateDataType();

		addWindowListener(new WindowAdapter() {	//Anonymous Inner Class
			public void windowClosing(WindowEvent e) {
				((Window)e.getSource()).dispose();
				System.out.println("AnonymousInnerClass");
			}

			public void windowClosed(WindowEvent e) {
				System.exit(0);
			}
			});
		addWindowListener(new AppListener());
	}

	public static void main(String[] args) {
		TopLevelClass test = new TopLevelClass();
		test.show();
	}
}
Running Example

Visa.java

public class Visa {
	private Citizen owner;
	private int validFor;
	
	public Visa(Citizen issuedOwner, int validForPeriod) {
		owner = issuedOwner;
		validFor = validForPeriod;
	}
	
	public boolean validate(Citizen possessor) {
		return possessor.equals(owner);
	}
}

Person.java

public abstract class Person {
	protected boolean gender;
	
	public final static boolean MALE = true;
	public final static boolean FEMALE = false;
	
	private String birthname;
	public String nickname;
	
	private Person() {}
	
	public Person(boolean gender, String name) {
		this.gender = gender;
		birthname = nickname = name;
	}
	
	protected boolean getGender()	{	return gender;		}
	public String getBirthname() 	{	return birthname;	}
	public abstract String say(String statement);
}
Concrete, Abstract classes and Interfaces
Interface is a "pure" abstract class -- no implementation, only variables
Abstract classes have some, but not all methods implemented (at least one abstract method or unimplemented interface)
Concrete classes have everything implemented and is only type instantiable by new.
Inheritance
Single inheritance
Implicit inheritance from class Object
AmericanCitizen.java
public class AmericanCitizen extends Person implements American, Citizen {
	private Visa myVisa;
	private int mySSN;
	
	public AmericanCitizen(boolean gender, String name, int SSN) {
		super(gender, name);
		mySSN = SSN;
	}
	
	public Visa getVisa()	{	return myVisa;	}
	public int getSSN()		{	return mySSN;	}
	public void setVisa(Visa visa) {	myVisa = visa;	}
	
	public String say(String statement) {
		String said = this.getBirthname() + ": " + statement;
		System.out.print(said);

		return said;
	}
	
	public static void main(String[] args) {
		AmericanCitizen me = new AmericanCitizen(Person.MALE, "David", 123456789);
		AmericanCitizen you = new AmericanCitizen(Person.FEMALE, "Jane", 987654321);
		Inspector police = new Inspector();
		
		me.setVisa(new Visa(me, 5));
		you.setVisa(new Visa(you, 5));
		
		me.say("hello\n");
		me.say("My SSN is: " + me.getSSN() + "\n");
		me.setVisa(you.getVisa());
		
		police.checkVisa(me);
	}
}
Inspector.java
public class Inspector extends AmericanCitizen {
	public Inspector() {
		super(Person.MALE, "Inspector", 0);
	}
	
	public boolean checkVisa(Citizen citizen) {
		if (!citizen.getVisa().validate(citizen)) {
			say("Fake Visa!\n");
			return false;
		}
		
		return true;
	}
}
Inheritance Challenges
Widget1.java
What is the output?
class Widget1 {
	protected static String str = "Widget1";

	public Widget1() {
		this.shared();
	}

	protected void shared() {
		System.out.println(str);
	}

	public static void main(String[] args) {
		Widget1 test = new Widget2();
		Widget1 test2 = new Widget1();

		System.out.println("\n" + test.str);
		System.out.println(((Widget2)test).str);
	}
}

class Widget2 extends Widget1 {
	protected static String str = "Widget2";

	protected Widget2() {
		this.shared();
	}

	public void shared() {
		System.out.println(str);
	}
}
Method and Field Resolution
Methods
The actual type of the object governs which implementation of a method is used.
Thus, Widget1 outputs "Widget1" while Widget2 outputs "Widget2" no matter whether it's cast as Widget1 or Widget2
Fields
The type of the reference governs which field is actually accessed.
Interfaces
Citizen.java
public interface Citizen {
	public Visa getVisa();
	public void setVisa(Visa visa);
}
American.java
public interface American {
	public int getSSN();
}
Interfaces can extend other interfaces
A class can implement multiple interfaces
Control Flow
Java's control flow constructs are the same as those in C++, minus goto (which is reserved but unused)
Statements and Blocks
Expression statements - assignment, pre/post-fix ++/--, method call, object creation. Ends with ;
Declaration statements - declare variables and optionally initialize its value - can appear ANYWHERE inside a block.
Blocks - group multiple statements into "one" logical statement (a compound statement)
Conditional
if (boolean-expression)
	statement1
else
	statement2
Switch
switch (value-expression) {
	case static-value1:
		statement1
	case static-value2:
		statement2
	...
	default:
		statement
}
fall-throughs and break;
caveat - value-expressions and static-values can't be float/double (imprecise number).
Also, case values must not change (literals or static variables)
While
while (boolean-expression)	//executes 0 or more times
	statement

do
	statement
while (boolean-expression)	//executes 1 or more times
For
for (initial-expression; boolean-expression; incremental-expression)
	statement

unwraps to:

{
	initial-expression;
	while (boolean-expression) {
		statement
		incremental-expression;
	}
}
Labels, Break, and Continue
label-name:
	statement
break [label-name];	//psuedo "goto"
continue;		//skips remainder of loop and evaluate boolean control expression
Return
if method has no return value, use
return;
if method has a return type,
return value;

where value has type to be returned
Exceptions
Types of Exceptions
Checked Exceptions
extend Exception
MUST be either
explicitly caught by a surrounding catch block
explicitly declared as a checked exception via the throws clause
Unchecked Exceptions
extend RuntimeException
DOES NOT need an explicit catch block or throws clause
throw
"How you raise exceptions"
Throw only classes of type Throwable - Exceptions extend Throwable
throw new java.io.IOException();
try, catch, finally
try blocks - "How you define the block of code where exceptions are 'watched for'"
catch clauses - "After an exception is thrown in a try block, determine how to deal with it"
finally clause - "After the try block is complete, run this no matter what/how"
Example
try {
	//
	//code that could throws IOException, among other exceptions
	//
} catch (IOException e) {
	//handle IOException
} catch (Exception ee) {
	//catch any exception
} finally {
	//clean up after the try block
}
Threads
Consult introductory systems text for understanding behind Threads
Basic - threads allow multiple things to happen "simultaneously" in Java
Mutual Exclusivity
synchronized keyword - forces mutual exclusivity on whatever method/object it acts on.
synchronized classes - ensures only one thread can be in the static class method at a time
synchronized methods - ensures only one thread can be in the class method at a time
synchronized objects - obtains lock on specific objects
Inter-Thread communication
wait - the thread waits to be notified (when certain conditions are met)
notify - notify any thread waiting on the object
notifyAll - notify all threads waiting on the object
Thread Management
sleep - give up execution time slice for a fixed amount of time
yield - give any other running thread its slice of execution time
//Dangerous and deprecated
suspend - make a running thread temporarily stop
resume - make a suspended thread running again
stop - permanently stop a thread

PingPong.java

class PingPong extends Thread {
	String word;
	int delay;

	PingPong(String whatToSay, int delayInterval) {
		word = whatToSay;
		delay = delayInterval;
	}
	public void run() {
		try {
			for (;;) {
				System.out.print(word + " ");
				sleep(delay);					//wait for delay ms
			}
		} catch (InterruptedException e) {
			return;								//end on any error
		}
	}

	public static void main(String[] args) {
		new PingPong("ping", 33).start();		//repeat 1/30 sec
			new PingPong("PONG", 100).start();		//repeat 1/10 sec
	}
}
java.util
Old time favorites
StringTokenizer, Date, Random
Collections API
A collections framework is a unified architecture for representing and manipulating collections
It consists of Interfaces, Implementations, and Algorithms
Interfaces

Implementations
  Implementations
Hash Table Resizable Array Balanced Tree Linked List
Interfaces Set HashSet   TreeSet  
List   ArrayList   LinkedList
Map HashMap   TreeMap  
Algorithms

java.util.Collections class

Collections - lots of concrete implementations of common algorithms and general utilities
binary search, reverse order, randomize, sort
synchronize Collection data types
make read-only Collection data types
Enumeration and Iterators
Iterator replaces Enumeration in the Collections API
Iterator allows the caller to remove elements from the underlying collection with well-defined semantics
Method names are shorter and more intuitive
Iterator - hasNext, next, remove
Enumeration - hasMoreElements, nextElement
java.awt
The AWT package is the core of Java's ability to do anything and everything graphical. The AWT is abstract in that creating a 'button' does not mean a specific look and feel to the button, but an 'abstract' button. This way, a Java applet/application running on a UNIX machine will have a Motif look and feel and a Java applet running on a Windows machine will have a Windows look and feel.
Historical note: the AWT was thrown together in a scant 6 weeks
AWT architecture delegated the "look and feel" responsibility to native peers
AWT Event Model handled the messages from native peers, transformed them into Java Events, and they are dispatched to the appropriate
AWT comes with a variety of graphical elements. Some of these include buttons, dialog boxes, scroll bars, and text fields. AWT also comes with a number of classes that are not necassarily something that appears on your screen. These include graphics contexts, images, and media trackers.

In order to actually use an AWT class, you need to have imported the java.awt package. From there instantiation of new objects is straight forward.

Examples later
java.applet
Creating Applets
create a class that extends java.applet.Applet
Make sure to fill in appropriate behavior in the Applet's life-cycle
init()
start()
run() (sometimes)
paint()
update() (sometimes)
Drawing in Applets
paint(Graphics g)
repaint(Graphics g)
update()
Examples later
java.awt.event
The AWT 1.0 Event Model
Event producers and consumers
Events are sorted and dispatched by the programmer
AWT10.java
import java.awt.*;
import java.applet.Applet;

public class AWT10 extends Applet {
	int xval=10, yval=10;

	public boolean mouseDown(Event evt, int x, int y){
		xval = x;
		yval = y;
		repaint();
		return true;
	}

	public void init() { }

	public void start() { } 

	public void paint(Graphics g) {
		g.setColor(Color.black);
		g.drawArc(xval,yval,40,40,0,360);
	}

}
The AWT 1.1 Event Model
Event producers and consumers
Events are sorted and dispatched within the AWT infrastructure
AWT11.java
import java.awt.*;
import java.applet.Applet;
import java.awt.event.MouseEvent;
import java.awt.event.MouseAdapter

public class AWT11 extends Applet{
	int xval=10, yval=10;

	public void init() {
		addMouseListener(new MouseAdapter() {
			public void mousePressed(MouseEvent e) {
				xval = e.getX();
				yval = e.getY();
				repaint;
			}
			});
	}

	public void start() { } 

	public void paint(Graphics g) {
		g.setColor(Color.black);
		g.drawArc(xval,yval,40,40,0,360);
	}

}
Live Example Subtlety
why Java is truly OO
Everything exists in classes
Proper encapsulation and protection of member fields and methods
why Java is truly typesafe
Implicit conversions between primitive types
Objects are strongly typed and will throw exceptions if improperly cast
why Java is Y2K compliant
time is held in 64bit (long)
The trend in Java is in server side applications, not client side applets...