Download Java Programming Language: Lecture 10 - Objects, Type System, and Virtual Machine - Prof. and more Assignments Programming Languages in PDF only on Docsity!
Prof. Su ECS 140A Lecture 10 1
Programming Languages
ECS 140A
13:40-15:00 Tu/Th
55 Roessler
Prof. Su ECS 140A Lecture 10 2
Announcements/reminders
- HW3 due May 7th
- Midterm on May 12th
- Covers everything up to Java
- Sample midterms will be posted on Smartsite
Prof. Su ECS 140A Lecture 10 3
Outline
- Objects in Java
- Classes, encapsulation, inheritance
- Type system
- Primitive types, interfaces, arrays, exceptions
- Generics (added in Java 1.5)
- Virtual machine
- Loader, verifier, linker, interpreter
- Bytecodes for method lookup
- Security issues
Prof. Su ECS 140A Lecture 10 4
Language Terminology
- Class, object - as in other languages
- Field – data member
- Method - member function
- Static members - class fields and methods
- this - self
- Package - set of classes in shared namespace
- Native method - method written in another
language, often C
Prof. Su ECS 140A Lecture 10 5
Java Classes and Objects
- Syntax similar to C++
- Object
- has fields and methods
- is allocated on heap, not run-time stack
- accessible through reference (only ptr assignment)
- garbage collected
- Dynamic lookup
- Similar in behavior to other languages
- Static typing => more efficient than Smalltalk
- Dynamic linking, interfaces => slower than C++
Prof. Su ECS 140A Lecture 10 6
Point Class
class Point { private int x; protected void setX (int y) {x = y;} public int getX() {return x;} Point(int xval) {x = xval;} // constructor };
- Visibility similar to C++, but not exactly (later slide)
Prof. Su ECS 140A Lecture 10 10
Visibility and access
- Four visibility distinctions
- public, private, protected, package
- Method can refer to
- private members of class it belongs to
- non-private members of all classes in same package
- protected members of superclasses (in diff package)
- public members of classes in visible packages Visibility determined by files system, etc. (outside language)
- Qualified names (or use import) java.lang.String.substring()
package class method
Prof. Su ECS 140A Lecture 10 11
Inheritance
- Similar to Smalltalk, C++
- Subclass inherits from superclass
- Single inheritance only (but Java has interfaces)
- Some additional features
- Conventions regarding super in constructor and finalize methods
- Final classes and methods
Prof. Su ECS 140A Lecture 10 12
Example subclass
class ColorPoint extends Point {
// Additional fields and methods
private Color c;
protected void setC (Color d) { c = d; }
public Color getC() { return c; }
// Define constructor
ColorPoint(int xval, Color cval) {
super(xval); // call Point constructor
c = cval; } // initialize ColorPoint field
Prof. Su ECS 140A Lecture 10 13
Class Object
- Every class extends another class
- Superclass is Object if no other class named
- Methods of class Object
- getClass – return the Class object representing class of the object
- toString – returns string representation of object
- equals – default object equality (not ptr equality)
- hashCode
- clone – makes a duplicate of an object
- wait, notify, notifyAll – used with concurrency
- finalize
Prof. Su ECS 140A Lecture 10 14
Constructors and Super
- Java guarantees constructor call for each object
- This must be preserved by inheritance
- Subclass constructor must call super constructor
- If first statement is not call to super, then call super() inserted automatically by compiler
- If superclass does not have a constructor with no args, then this causes compiler error
- Exception to rule: if one constructor invokes another, then it is responsibility of second constructor to call super, e.g., ColorPoint() { ColorPoint(0,blue);} is compiled without inserting call to super
- Different conventions for finalize and super
- Compiler does not force call to super finalize
Prof. Su ECS 140A Lecture 10 15
Final classes and methods
- Restrict inheritance
- Final classes and methods cannot be redefined
- Example java.lang.String
- Reasons for this feature
- Important for security
- Programmer controls behavior of all subclasses
- Critical because subclasses produce subtypes
- Compare to C++ virtual/non-virtual
- Method is “virtual” until it becomes final
Prof. Su ECS 140A Lecture 10 19
Subtyping
- Primitive types
- Conversions: int -> long, double -> long, …
- Class subtyping similar to C++
- Subclass produces subtype
- Single inheritance => subclasses form tree
- Interfaces
- Completely abstract classes
- Multiple subtyping
- Interface can have multiple subtypes (implements, extends)
- Arrays
- Covariant subtyping – not consistent with semantic principles
Prof. Su ECS 140A Lecture 10 20
Java class subtyping
- Signature Conformance
- Subclass method signatures must conform to those of superclass
- Three ways signature could vary
- Argument types
- Return type
- Exceptions How much conformance is needed in principle?
- Java rule
- Java 1.1: Arguments and returns must have identical types, may remove exceptions
- Java 1.5: covariant return type specialization
Prof. Su ECS 140A Lecture 10 21
Interface subtyping: example
interface Shape { public float center(); public void rotate(float degrees); } interface Drawable { public void setColor(Color c); public void draw(); } class Circle implements Shape, Drawable { // does not inherit any implementation // but must define Shape, Drawable methods }
Prof. Su ECS 140A Lecture 10 22
Properties of interfaces
- Flexibility
- Allows subtype graph instead of tree
- Avoids problems with multiple inheritance of implementations (remember C++ “diamond”)
- Cost
- Offset in method lookup table not known at compile
- Different bytecodes for method lookup
- one when class is known (the standard one)
- one when only interface is known
- search for location of method
- cache for use next time this call is made (from this line)
Prof. Su ECS 140A Lecture 10 23
Array types
- Automatically defined
- Array type T[ ] exists for each class, interface type T
- Cannot extend array types ( array types are final)
- Multi-dimensional arrays are arrays of arrays: T[ ] [ ]
- Treated as reference type
- An array variable is a pointer to an array, can be null
- Example: Circle[] x = new Circle[array_size]
- Anonymous array expression: new int[] {1,2,3, ... 10}
- Every array type is a subtype of Object[ ], Object
- Length of array is not part of its static type
Prof. Su ECS 140A Lecture 10 24
Array subtyping
- Covariance
- if S <: T then S[ ] <: T[ ]
- Standard type error
class A {…}
class B extends A {…}
B[ ] bArray = new B[10]
A[ ] aArray = bArray // considered OK since B[] <: A[]
aArray[0] = new A() // compiles, but run-time error
// raises ArrayStoreException
Prof. Su ECS 140A Lecture 10 28
Try/finally blocks
- Exceptions are caught in try blocks try { statements } catch (ex-type1 identifier1) { statements } catch (ex-type2 identifier2) { statements } finally { statements }
- Implementation: finally compiled to jsr
Prof. Su ECS 140A Lecture 10 29
Why define new exception types?
- Exception may contain data
- Class Throwable includes a string field so that
cause of exception can be described
- Pass other data by declaring additional fields or
methods
- Subtype hierarchy used to catch exceptions
catch { … }
will catch any exception from any subtype of
exception-type and bind object to identifier
Prof. Su ECS 140A Lecture 10 30
Outline
- Objects in Java
- Classes, encapsulation, inheritance
- Type system
- Primitive types, interfaces, arrays, exceptions
- Generics (added in Java 1.5)
- Virtual machine
- Loader, verifier, linker, interpreter
- Bytecodes for method lookup
- Security issues
Prof. Su ECS 140A Lecture 10 31
Java Generic Programming
- Java has class Object
- Supertype of all object types
- This allows “subtype polymorphism”
- Can apply operation on class T to any subclass S <: T
- Java 1.0 – 1.4 did not have templates
- No parametric polymorphism
- Many considered this the biggest deficiency of Java
- Java type system does not let you “cheat”
- Can cast from supertype to subtype
- Cast is checked at run time
Prof. Su ECS 140A Lecture 10 32
Example generic construct: Stack
- Stacks possible for any type of object
- For any type t, can have type stack_of_t
- Operations push, pop work for any type
- In C++, would write generic stack class template class Stack { private: t data; Stack * next; public: void push (t* x) { … } t* pop ( ) { … } };
- What can we do in Java 1.0?
Prof. Su ECS 140A Lecture 10 33
Java 1.0 vs Generics
class Stack { void push(Object o) { ... } Object pop() { ... } ...}
String s = "Hello"; Stack st = new Stack(); ... st.push(s); ... s = (String) st.pop();
class Stack { void push(A a) { ... } A pop() { ... } ...}
String s = "Hello"; Stack st = new Stack(); st.push(s); ... s = st.pop();
Prof. Su ECS 140A Lecture 10 37
Example: Hash Table
interface Hashable { int HashCode (); }; class HashTable < Key extends Hashable, Value> { void Insert (Key k, Value v) { int bucket = k.HashCode(); InsertAt (bucket, k, v); } …
}; This expression must typecheck
Use “Key extends Hashable”
Prof. Su ECS 140A Lecture 10 38
Priority Queue Example
interface Comparable { boolean lessThan(I); }
class PriorityQueue> { T queue[ ] ; … void insert(T t) { ... if ( t.lessThan(queue[i]) ) ... } T remove() { ... } ... }
Why is this form needed? Less: t t -> t is contravariant in t
Prof. Su ECS 140A Lecture 10 39
Wildcards
public void draw(List shape) { for(Shape s: shape) { s.draw(this); } }
public void draw(List shape) { for(Shape s: shape) { s.draw(this); } }
“? extends Shape” is an example of wildcards
Prof. Su ECS 140A Lecture 10 40
Implementing Generics
- Type erasure
- Compile-time type checking uses generics
- Compiler eliminates generics by erasing them
- Compile List to List, T to Object, insert casts
- “Generics are not templates”
- Generic declarations are typechecked
- Generics are compiled once and for all
- No instantiation
- No “code bloat”
Prof. Su ECS 140A Lecture 10 41
Next time
- Java implementation, JVM
- Security issues