Beruflich Dokumente
Kultur Dokumente
Outline
The Java Programming
Language Language Overview -- next lecture (separate slides) --
• History and design goals Virtual machine overview
Classes and Inheritance • Loader and initialization
• Object features • Linker and verifier
• Bytecode interpreter
• Encapsulation
John Mitchell • Inheritance Method lookup
• four different bytecodes
Types and Subtyping
Verifier analysis
• Primitive and ref types
• Interfaces; arrays
Implementation of generics
• Exception hierarchy Security
• Buffer overflow
Generics
Reading: Chapter 13 + Gilad Bracha, Generics in the Java • Java “sandbox”
• Subtype polymorphism. • Type safety and attacks
Programming Language, Sun Microsystems, 2004 (see web site). generic programming
1
Java Release History Enhancements in JDK 5 (= Java 1.5)
2
Object initialization Garbage Collection and Finalize
Java guarantees constructor call for each object Objects are garbage collected
• Memory allocated • No explicit free
• Constructor called to initialize memory • Avoids dangling pointers and resulting type errors
• Some interesting issues related to inheritance Problem
We’ll discuss later …
• What if object has opened file or holds lock?
Cannot do this (would be bad C++ style anyway): Solution
• Obj* obj = (Obj*)malloc(sizeof(Obj)); • finalize method, called by the garbage collector
Static fields of class initialized at class load time – Before space is reclaimed, or when virtual machine exits
• Talk about class loading later – Space overflow is not really the right condition to trigger
finalization when an object holds a lock...)
• Important convention: call super.finalize
3
Class Object Constructors and Super
Every class extends another class Java guarantees constructor call for each object
• Superclass is Object if no other class named This must be preserved by inheritance
Methods of class Object • Subclass constructor must call super constructor
• GetClass – return the Class object representing class of the object – If first statement is not call to super, then call super()
• ToString – returns string representation of object inserted automatically by compiler
• equals – default object equality (not ptr equality) – If superclass does not have a constructor with no args,
• hashCode then this causes compiler error (yuck)
• Clone – makes a duplicate of an object – Exception to rule: if one constructor invokes another, then it
is responsibility of second constructor to call super, e.g.,
• wait, notify, notifyAll – used with concurrency
ColorPoint() { ColorPoint(0,blue);}
• finalize
is compiled without inserting call to super
Different conventions for finalize and super
– Compiler does not force call to super finalize
4
Subtyping Java class subtyping
Primitive types Signature Conformance
• Conversions: int -> long, double -> long, … • Subclass method signatures must conform to those of
Class subtyping similar to C++ superclass
• Subclass produces subtype Three ways signature could vary
• Single inheritance => subclasses form tree • Argument types
Interfaces • Return type
• Completely abstract classes • Exceptions
– no implementation
How much conformance is needed in principle?
• Multiple subtyping
– Interface can have multiple subtypes (implements, extends) Java rule
Arrays • Java 1.1: Arguments and returns must have identical
• Covariant subtyping – not consistent with semantic principles
types, may remove exceptions
• Java 1.5: covariant return type specialization
5
Covariance problem again … Afterthought on Java arrays
Remember Simula problem Date: Fri, 09 Oct 1998 09:41:05 -0600
From: bill joy
• If A <: B, then A ref <: B ref
Subject: …[discussion about java genericity]
• Needed run-time test to prevent bad assignment
• Covariance for assignable cells is not right in principle actually, java array covariance was done for less noble reasons …: it
made some generic "bcopy" (memory copy) and like operations much
Explanation easier to write...
• interface of “T reference cell” is I proposed to take this out in 95, but it was too late (...).
put : T → T ref i think it is unfortunate that it wasn't taken out...
get : T ref → T it would have made adding genericity later much cleaner, and [array
• Remember covariance/contravariance of functions covariance] doesn't pay for its complexity today.
wnj
6
Outline Java Generic Programming
Objects in Java Java has class Object
• Classes, encapsulation, inheritance • Supertype of all object types
Type system • This allows “subtype polymorphism”
• Primitive types, interfaces, arrays, exceptions – Can apply operation on class T to any subclass S <: T
Generics (added in Java 1.5) Java 1.0 – 1.4 did not have generics
• Basics, wildcards, … • No parametric polymorphism
Virtual machine • Many considered this the biggest deficiency of Java
• Loader, verifier, linker, interpreter
Java type system does not let you “cheat”
• Bytecodes for method lookup
• Can cast from supertype to subtype
Security issues
• Cast is checked at run time
Stacks possible for any type of object class Stack { class Stack<A> {
• For any type t, can have type stack_of_t void push(Object o) { ... } void push(A a) { ... }
• Operations push, pop work for any type Object pop() { ... } A pop() { ... }
...} ...}
In C++, would write generic stack class
template <type t> class Stack {
String s = "Hello"; String s = "Hello";
private: t data; Stack<t> * next;
public: void push (t* x) { … }
Stack st = new Stack(); Stack<String> st =
t* pop ( ){…} ... new Stack<String>();
}; st.push(s); st.push(s);
What can we do in Java 1.0? ... ...
s = (String) st.pop(); s = st.pop();
Why no generics in early Java ? JSR 14 Java Generics (Java 1.5, “Tiger”)
7
Java generics are type checked Example
Generic interface
A generic class may use operations on objects
interface Collection<A> { interface Iterator<E> {
of a parameter type public void add (A x); E next();
• Example: PriorityQueue<T> … if x.less(y) then … public Iterator<A> iterator (); boolean hasNext();
Two p
possible solutions } }
• C++: Link and see if all operations can be resolved Generic class implementing Collection interface
class LinkedList<A> implements Collection<A> {
• Java: Type check and compile generics w/o linking
protected class Node {
– May need additional information about type parameter
A elt;
• What methods are defined on parameter type?
Node next = null;
• Example: PriorityQueue<T extends ...>
Node (A elt) { this.elt = elt; }
}
...
}
}
Meaning: Any representative from a family of types Bounded polymorphism
• unbounded wildcard ? • printString : ∀t <: Printable . t → String
– all types
for every subtype t of Printable function from t to String
• lower-bound wildcard ? extends Supertype
– all types that are subtypes of Supertype
• upper-bound wildcard ? super Subtype F-Bounded polymorphism
– all types that are supertypes of Subtype • max : ∀t <: Comparable (t) . t × t → t
for every subtype t of … return max of object and argument
Example
Subtyping public
bli static
t ti <T extends
t d Comparable<T>>
C bl <T>> T max(Collection<T>
(C ll ti <T> coll)
ll) {
T candidate = coll.iterator().next();
interface A { public int compareTo(A arg); for (T elt : coll) {
int anotherMethod (A arg); … } if (candidate.compareTo(elt) < 0) candidate = elt;
<: }
interface Comparable<A> { public int compareTo(A arg); } return candidate;
}
candidate.compareTo : T → int
8
This would typecheck without F-bound … Generics are not co/contra-variant
Generic interface Object Array example (review)
interface Comparable<T> { public int compareTo(T arg); … } Integer[] ints = new Integer[] {1,2,3};
Number[] nums = ints;
Example nums[2] = 3.14; // array store -> exception at run time
public
bli static
t ti <T extends
t d Comparable<T>>
C bl <T>> T max(Collection<T>
(C ll ti <T> coll)
ll) {
T candidate = coll.iterator().next(); List example
for (T elt : coll) { List<Integer> ints = Arrays.asList(1,2,3);
if (candidate.compareTo(elt) < 0) candidate = elt; List<Number> nums = ints; // compile-time error
} • Second does not compile because
return candidate;
List<Integer> <: List<Number>
} Object
candidate.compareTo : T → int
How could you write an implementation of this interface?
Enhancements in JDK 5
• http://java.sun.com/j2se/1.5.0/docs/guide/language/i
ndex.html
J2SE 5.0 in a Nutshell
• http://java.sun.com/developer/technicalArticles/relea
ses/j2se15/
Generics
• http://www.langer.camelot.de/Resources/Links/Java
Generics.htm