Sie sind auf Seite 1von 9

CS 242

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

Origins of the language Design Goals


‹James Gosling and others at Sun, 1990 - 95 ‹Portability
‹Oak language for “set-top box” • Internet-wide distribution: PC, Unix, Mac
• small networked device with television display ‹Reliability
– graphics • Avoid p
program
g crashes and error messages
g
– execution of simple programs
– communication between local program and remote site
‹Safety
– no “expert programmer” to deal with crash, etc. • Programmer may be malicious
‹Internet application ‹Simplicity and familiarity
• simple language for writing programs that can be • Appeal to average programmer; less complex than C++
transmitted over network ‹Efficiency
• Important but secondary

General design decisions Java System


‹Simplicity ‹The Java programming language
• Almost everything is an object ‹Compiler and run-time system
• All objects on heap, accessed through pointers • Programmer compiles code
• No functions, no multiple inheritance, no go to, no • p
Compiled code transmitted on network
operator overloading, few automatic coercions • Receiver executes on interpreter (JVM)
‹Portability and network transfer • Safety checks made before/during execution
• Bytecode interpreter on many platforms ‹Library, including graphics, security, etc.
‹Reliability and Safety • Large library made it easier for projects to adopt Java
• Typed source and typed bytecode language • Interoperability
• Run-time type and bounds checks – Provision for “native” methods
• Garbage collection

1
Java Release History Enhancements in JDK 5 (= Java 1.5)

‹1995 (1.0) – First public release ‹ Generics


• Polymorphism and compile-time type safety (JSR 14)
‹1997 (1.1) – Inner classes ‹ Enhanced for Loop
• For iterating over collections and arrays (JSR 201)
‹2001 (1.4) – Assertions
‹ Autoboxing/Unboxing
• Verify programmers understanding of code • Automatic conversion between primitive,
primitive wrapper types (JSR 201)
‹2004 (1.5) – Tiger ‹ Typesafe Enums
• Enumerated types with arbitrary methods and fields (JSR 201)
• Generics, foreach, Autoboxing/Unboxing, ‹ Varargs
• Typesafe Enums, Varargs, Static Import, • Puts argument lists into an array; variable-length argument lists
• Annotations, concurrency utility library ‹ Static Import
• Avoid qualifying static members with class names (JSR 201)
‹ Annotations (Metadata)
http://java.sun.com/developer/technicalArticles/releases/j2se15/ • Enables tools to generate code from annotations (JSR 175)
Improvements through Java Community Process ‹ Concurrency utility library, led by Doug Lea (JSR-166)

Outline Language Terminology


‹Objects in Java ‹Class, object - as in other languages
• Classes, encapsulation, inheritance ‹Field – data member
‹Type system
‹Method - member function
• Primitive types, interfaces, arrays, exceptions
‹Generics (added in Java 1.5) ‹Static members - class fields and methods
• Basics, wildcards, … ‹this - self
‹Virtual machine ‹Package - set of classes in shared namespace
• Loader, verifier, linker, interpreter ‹Native method - method written in another
• Bytecodes for method lookup language, often C
‹Security issues

Java Classes and Objects Point Class


‹Syntax similar to C++ class Point {
private int x;
‹Object
protected void setX (int y) {x = y;}
• has fields and methods
public int getX() {return x;}
• p, not run-time stack
is allocated on heap, Point(int xval) {x = xval;} // constructor
• accessible through reference (only ptr assignment) };
• garbage collected
‹Dynamic lookup
• Similar in behavior to other languages
• Static typing => more efficient than Smalltalk • Visibility similar to C++, but not exactly (later slide)
• Dynamic linking, interfaces => slower than C++

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

Encapsulation and packages Visibility and access


‹Every field, method ‹Four visibility distinctions
package
belongs to a class • public, private, protected, package
class
‹Every class is part of field ‹Method can refer to
some ppackageg • p
private members of class it belongs
g to
method
th d
• Can be unnamed default • non-private members of all classes in same package
package • protected members of superclasses (in diff package)
• File declares which package • public members of classes in visible packages
package code belongs to
class Visibility determined by files system, etc. (outside language)
field ‹Qualified names (or use import)
method • java.lang.String.substring()

package class method

Inheritance Example subclass


‹Similar to Smalltalk, C++ class ColorPoint extends Point {
‹Subclass inherits from superclass // Additional fields and methods
• Single inheritance only (but Java has interfaces) private Color c;
protected void setC (Color d) {c = d;}
‹Some additional features
public Color getC() {return c;}
• Conventions regarding super in constructor and
finalize methods // Define constructor
• Final classes and methods ColorPoint(int xval, Color cval) {
super(xval); // call Point constructor
c = cval; } // initialize ColorPoint field
};

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

Final classes and methods Outline


‹Restrict inheritance ‹Objects in Java
• Final classes and methods cannot be redefined • Classes, encapsulation, inheritance
‹Example ‹Type system
• Primitive types, interfaces, arrays, exceptions
j
java.lang.String
g g
‹Generics (added in Java 1.5)
‹Reasons for this feature
• Basics, wildcards, …
• Important for security
– Programmer controls behavior of all subclasses
‹Virtual machine
– Critical because subclasses produce subtypes • Loader, verifier, linker, interpreter
• Compare to C++ virtual/non-virtual • Bytecodes for method lookup
– Method is “virtual” until it becomes final ‹Security issues

Java Types Classification of Java types


‹ Two general kinds of types Reference Types
• Primitive types – not objects Object
– Integers, Booleans, etc
• Reference types Object[ ] Throwable
– Classes, interfaces, arrays
– No syntax distinguishing Object * from Object Shape Shape[ ]
Exception
‹ Static type checking types
• Every expression has type, determined from its parts Circle Square Circle[ ] Square[ ]
• Some auto conversions, many casts are checked at run time
user-defined arrays
• Example, assuming A <: B
– If A x, then can use x as argument to method that requires B Primitive Types
– If B x, then can try to cast x to A
boolean int byte … float long
– Downcast checked at run-time, may raise exception

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

Interface subtyping: example Properties of interfaces


interface Shape {
‹Flexibility
public float center();
• Allows subtype graph instead of tree
public void rotate(float degrees);
• Avoids problems with multiple inheritance of
}
implementations (remember C++ “diamond”)
interface Drawable {
public void setColor(Color c); ‹Cost
public void draw(); • Offset in method lookup table not known at compile
} • Different bytecodes for method lookup
class Circle implements Shape, Drawable { – one when class is known
// does not inherit any implementation – one when only interface is known
// but must define Shape, Drawable methods • search for location of method
• cache for use next time this call is made (from this line)
}
More about this later …

Array types Array subtyping


‹Automatically defined ‹Covariance
• Array type T[ ] exists for each class, interface type T • if S <: T then S[ ] <: T[ ]
• Cannot extended array types (array types are final) ‹Standard type error
• Multi-dimensional arrays are arrays of arrays: T[ ] [ ] class A {…}
{ }
‹Treated as reference type class B extends A {…}
• An array variable is a pointer to an array, can be null B[ ] bArray = new B[10]
• Example: Circle[] x = new Circle[array_size] A[ ] aArray = bArray // considered OK since B[] <: A[]
• Anonymous array expression: new int[] {1,2,3, ... 10} aArray[0] = new A() // compiles, but run-time error
‹Every array type is a subtype of Object[ ], Object // raises ArrayStoreException

• Length of array is not part of its static type

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

Java Exceptions Exception Classes


‹Similar basic functionality to ML, C++
Throwable
• Constructs to throw and catch exceptions
• Dynamic scoping of handler
Exception Runtime Error
‹Some differences
Exception
E ti
• An exception is an object from an exception class checked
• Subtyping between exception classes exceptions
– Use subtyping to match type of exception or pass it on … User-defined Unchecked exceptions
– Similar functionality to ML pattern matching in handler exception classes
• Type of method includes exceptions it can throw
– Actually, only subclasses of Exception (see next slide)
‹If a method may throw a checked exception,
then this must be in the type of the method

Try/finally blocks Why define new exception types?


‹Exceptions are caught in try blocks ‹Exception may contain data
try { • Class Throwable includes a string field so that cause
statements of exception can be described
} catch (ex-type1 identifier1) { • Pass other data by declaring additional fields or
statements methods
th d
} catch (ex-type2 identifier2) { ‹Subtype hierarchy used to catch exceptions
statements catch <exception-type> <identifier> { … }
} finally { will catch any exception from any subtype of
statements exception-type and bind object to identifier
}
‹Implementation: finally compiled to jsr

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

Example generic construct: Stack Java 1.0 vs Generics

‹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”)

‹Many proposals ‹Adopts syntax on previous slide


‹Basic language goals seem clear ‹Adds auto boxing/unboxing
‹Details take some effort to work out User conversion Automatic conversion
• Exact typing constraints
• Implementation Stack<Integer> st = Stack<Integer> st =
– Existing virtual machine?
new Stack<Integer>(); new Stack<Integer>();
– Additional bytecodes?
– Duplicate code for each instance?
st.push(new Integer(12)); st.push(12);
– Use same code (with casts) for all instances ... ...
int i = (st.pop()).intValue(); int i = st.pop();
Java Community proposal (JSR 14) incorporated into Java 1.5

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; }
}
...
}

Wildcards Type concepts for understanding Generics

‹ Example ‹Parametric polymorphism


void printElements(Collection<?> c) { • max : ∀t ((t × t) → bool) → ((t × t) → t)
for (Object e : c)
System.out.println(e); given lessThan function return max of two arguments

}
‹ 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

F-bounded subtyping Example static max method


‹ Generic interface ‹ Generic interface
interface Comparable<T> { public int compareTo(T arg); } interface Comparable<T> { public int compareTo(T arg); … }
– x.compareTo(y) = negative, 0, positive if y is < = > x

‹ 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?

Return to wildcards Implementing Generics


‹ Recall example ‹Type erasure
void printElements(Collection<?> c) { • Compile-time type checking uses generics
for (Object e : c) • Compiler eliminates generics by erasing them
System.out.println(e); – Compile List<T> to List, T to Object, insert casts
}
‹ Compare to ‹“Generics are not templates”
void printElements(Collection<Object> c) { • Generic declarations are typechecked
for (Object e : c)
System.out.println(e);
• Generics are compiled once and for all
– No instantiation
}
– No “code bloat”
• This version is much less useful than the old one
– Wildcard allows call with kind of collection as a parameter,
– Alternative only applies to Collection<Object>, not a supertype of More later when we talk about virtual machine …
other kinds of collections!

Additional links for material not in book

‹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

Das könnte Ihnen auch gefallen