CS 242 Outline Java � Virtual machine overview � Language Overview • Loader and initialization • History and design goals • Linker and verifier � Classes and Inheritance • Bytecode interpreter • Object features � Method lookup • Encapsulation John Mitchell • four different bytecodes • Inheritance � Verifier analysis � Types and Subtyping � Implementation of generics • Primitive and ref types � Security • Interfaces; arrays • Buffer overflow • Exception hierarchy • Java “sandbox” • Subtype polymorphism and • Type safety and attacks generic programming Origins of the language Design Goals � James Gosling and others at Sun, 1990 - 95 � Portability • Internet-wide distribution: PC, Unix, Mac � Oak language for “set-top box” � Reliability • small networked device with television display – graphics • Avoid program crashes and error messages – execution of simple programs � Safety – communication between local program and remote site • Programmer may be malicious – no “expert programmer” to deal with crash, etc. � Simplicity and familiarity � Internet application • Appeal to average programmer; less complex than C++ • simple language for writing programs that can be 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 • 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) � Generics � 1995 (1.0) – First public release • polymorphism and compile-time type safety (JSR 14) � 1997 (1.1) – Nested classes � Enhanced for Loop • for iterating over collections and arrays (JSR 201) • Support for function objects � Autoboxing/Unboxing � 2001 (1.4) – Assertions • automatic conversion between primitive, wrapper types (JSR 201) � Typesafe Enums • Verify programmers understanding of code • enumerated types with arbitrary methods and fields (JSR 201) � 2004 (1.5) – Tiger � Varargs • Generics, foreach, Autoboxing/Unboxing, • puts argument lists into an array; variable-length argument lists � Static Import • Typesafe Enums, Varargs, Static Import, • avoid qualifying static members with class names (JSR 201) • Annotations, concurrency utility library � Annotations (Metadata) http://java.sun.com/developer/technicalArticles/releases/j2se15/ • enables tools to generate code from annotations (JSR 175) � Concurrency utility library, led by Doug Lea (JSR-166) Improvements through Java Community Process 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 � Static members - class fields and methods � Generics (added in Java 1.5) � this - self • Basics, wildcards, … � 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;} • is allocated on heap, not run-time stack Point(int xval) {x = xval;} // constructor • accessible through reference (only ptr assignment) }; • garbage collected � Dynamic lookup • Similar in behavior to other languages • Visibility similar to C++, but not exactly (later slide) • Static typing => more efficient than Smalltalk • 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 � Method can refer to field some package • private members of class it belongs to method • 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 Visibility determined by files system, etc. (outside language) class field � Qualified names (or use import) • java.lang.String.substring() method package class method Inheritance Example subclass � Similar to Smalltalk, C++ class ColorPoint extends Point { // Additional fields and methods � Subclass inherits from superclass private Color c; • Single inheritance only (but Java has interfaces) protected void setC (Color d) {c = d;} � Some additional features public Color getC() {return c;} • Conventions regarding super in constructor and // Define constructor finalize methods ColorPoint(int xval, Color cval) { • Final classes and methodS 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() inserted automatically by compiler • ToString – returns string representation of object – If superclass does not have a constructor with no args, • equals – default object equality (not ptr equality) then this causes compiler error (yuck) • hashCode – Exception to rule: if one constructor invokes another, then it • Clone – makes a duplicate of an object 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 � Objects in Java � Restrict inheritance • Classes, encapsulation, inheritance • Final classes and methods cannot be redefined � Type system � Example • Primitive types, interfaces, arrays, exceptions java.lang.String � Generics (added in Java 1.5) � Reasons for this feature • Basics, wildcards, … • Important for security � Virtual machine – Programmer controls behavior of all subclasses • Loader, verifier, linker, interpreter – Critical because subclasses produce subtypes • Bytecodes for method lookup • Compare to C++ virtual/non-virtual � Security issues – Method is “virtual” until it becomes final Java Types Classification of Java types Reference Types � Two general kinds of times • Primitive types – not objects Object – Integers, Booleans, etc Object[ ] Throwable • Reference types – 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 – Can use A x and type 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
Recommend
More recommend