Presentation is loading. Please wait.

Presentation is loading. Please wait.

Intro to Java L. Grewe. Java history James Gosling and others at Sun, 1990 - 95 James Gosling and others at Sun, 1990 - 95 Internet application Internet.

Similar presentations


Presentation on theme: "Intro to Java L. Grewe. Java history James Gosling and others at Sun, 1990 - 95 James Gosling and others at Sun, 1990 - 95 Internet application Internet."— Presentation transcript:

1 Intro to Java L. Grewe

2 Java history James Gosling and others at Sun, 1990 - 95 James Gosling and others at Sun, 1990 - 95 Internet application Internet application simple language for writing programs that can be transmitted over networksimple language for writing programs that can be transmitted over network

3 Some Goals Portability Portability Internet-wide distribution: PC, Unix, MacInternet-wide distribution: PC, Unix, Mac Reliability Reliability Avoid program crashes and error messagesAvoid program crashes and error messages Safety Safety Programmer may be maliciousProgrammer may be malicious Simplicity and familiarity Simplicity and familiarity Appeal to average programmer; less complex than C++Appeal to average programmer; less complex than C++ Efficiency Efficiency Important but secondaryImportant but secondary

4 Characteristics Simplicity Simplicity Everything an objectEverything an object All objects on heap, accessed through pointersAll objects on heap, accessed through pointers no functionsno functions no multiple inheritance,no multiple inheritance, no operator overloadingno operator overloading Portability Portability Bytecode interpreter on many platformsBytecode interpreter on many platforms Reliability and Safety Reliability and Safety Run-time type and bounds checksRun-time type and bounds checks Garbage collectionGarbage collection

5 Java System The Java programming language The Java programming language Compiler and run-time system Compiler and run-time system Programmer compiles codeProgrammer compiles code Compiled code transmitted on networkCompiled code transmitted on network Receiver executes on interpreter (JVM)Receiver executes on interpreter (JVM) Safety checks made before/during executionSafety checks made before/during execution Library, including graphics, security, etc. Library, including graphics, security, etc. Large libraryLarge library Interoperability Interoperability Provision for “native” methodsProvision for “native” methods

6 Java Release History 1995 (1.0) – First public release 1995 (1.0) – First public release 1997 (1.1) – Inner classes 1997 (1.1) – Inner classes 2001 (1.4) – Assertions 2001 (1.4) – Assertions Verify programmers understanding of codeVerify programmers understanding of code 2004 (1.5) – Tiger 2004 (1.5) – Tiger Generics, foreach, Autoboxing/Unboxing,Generics, foreach, Autoboxing/Unboxing, Typesafe Enums, Varargs, Static Import,Typesafe Enums, Varargs, Static Import, Annotations, concurrency utility libraryAnnotations, concurrency utility library 2006 (1.6) – SE 6 2006 (1.6) – SE 6

7 Enhancements since JDK 5 (= Java 1.5) Generics Generics Polymorphism and compile-time type safety (JSR 14)Polymorphism and compile-time type safety (JSR 14) Enhanced for Loop Enhanced for Loop For iterating over collections and arrays (JSR 201)For iterating over collections and arrays (JSR 201) Autoboxing/Unboxing Autoboxing/Unboxing Automatic conversion between primitive, wrapper types (JSR 201)Automatic conversion between primitive, wrapper types (JSR 201) Typesafe Enums Typesafe Enums Enumerated types with arbitrary methods and fields (JSR 201)Enumerated types with arbitrary methods and fields (JSR 201) Varargs Varargs Puts argument lists into an array; variable-length argument listsPuts argument lists into an array; variable-length argument lists Static Import Static Import Avoid qualifying static members with class names (JSR 201)Avoid qualifying static members with class names (JSR 201) Annotations (Metadata) Annotations (Metadata) Enables tools to generate code from annotations (JSR 175)Enables tools to generate code from annotations (JSR 175) Concurrency utility library Concurrency utility library

8 Language Terminology Class, object Class, object Field – data member Field – data member Method - member function Method - member function Static members - class fields and methods Static members - class fields and methods this - self this - self Package - set of classes in shared namespace Package - set of classes in shared namespace Native method - method written in another language, often C Native method - method written in another language, often C

9 Java Classes and Objects Syntax similar to C++ Syntax similar to C++ Object Object has fields and methodshas fields and methods is allocated on heap, not run-time stackis allocated on heap, not run-time stack accessible through reference (only ptr assignment)accessible through reference (only ptr assignment) garbage collectedgarbage collected Dynamic lookup Dynamic lookup Similar in behavior to other languagesSimilar in behavior to other languages Static typing => more efficient than SmalltalkStatic typing => more efficient than Smalltalk Dynamic linking, interfaces => slower than C++Dynamic linking, interfaces => slower than C++

10 Template for Class Definition class { } Import Statements Class Comment Class Name Fields/Variables Methods (incl. Constructor) Methods (incl. Constructor)

11 Point Class class Point { private int x; private int x; protected void setX (int y) {x = y;} protected void setX (int y) {x = y;} public int getX() {return x;} public int getX() {return x;} Point(int xval) {x = xval;} // constructor Point(int xval) {x = xval;} // constructor};

12 Object initialization Java guarantees constructor call for each object Java guarantees constructor call for each object Memory allocatedMemory allocated Constructor called to initialize memoryConstructor called to initialize memory Some interesting issues related to inheritanceSome interesting issues related to inheritance

13 Garbage Collection and Finalize Objects are garbage collected Objects are garbage collected No explicit freeNo explicit free Avoids dangling pointers and resulting type errorsAvoids dangling pointers and resulting type errors Problem Problem What if object has opened file or?What if object has opened file or? Solution Solution finalize method, called by the garbage collectorfinalize method, called by the garbage collector Before space is reclaimed, or when virtual machine exits Before space is reclaimed, or when virtual machine exits

14 Encapsulation and packages Every field, method belongs to a class Every field, method belongs to a class Every class is part of some package Every class is part of some package Can be unnamed default packageCan be unnamed default package File declares which package code belongs toFile declares which package code belongs to package class field method package class field method

15 Access Four access distinctions Four access distinctions public, private, protected, packagepublic, private, protected, package Method can refer to Method can refer to private members of class it belongs toprivate members of class it belongs to non-private members of all classes in same packagenon-private members of all classes in same package protected members of superclasses (in diff package)protected members of superclasses (in diff package) public members of classes in visible packagespublic members of classes in visible packages Visibility determined by files system, etc. (outside language) Qualified names (or use import) Qualified names (or use import) java.lang.String.substring()java.lang.String.substring() package class method

16 Inheritance Similar to Smalltalk, C++ Similar to Smalltalk, C++ Subclass inherits from superclass Subclass inherits from superclass Single inheritance only (but Java has interfaces)Single inheritance only (but Java has interfaces)

17 Example subclass class ColorPoint extends Point { // Additional fields and methods // Additional fields and methods private Color c; private Color c; protected void setC (Color d) {c = d;} protected void setC (Color d) {c = d;} public Color getC() {return c;} public Color getC() {return c;} // Define constructor // Define constructor ColorPoint(int xval, Color cval) { ColorPoint(int xval, Color cval) { super(xval); // call Point constructor super(xval); // call Point constructor c = cval; } // initialize ColorPoint field c = cval; } // initialize ColorPoint field }; };

18 Class Object Every class extends another class Every class extends another class Superclass is Object if no other class namedSuperclass is Object if no other class named Methods of class Object Methods of class Object GetClass – return the Class object representing class of the objectGetClass – return the Class object representing class of the object ToString – returns string representation of objectToString – returns string representation of object equals – default object equality (not ptr equality)equals – default object equality (not ptr equality) hashCodehashCode Clone – makes a duplicate of an objectClone – makes a duplicate of an object wait, notify, notifyAll – used with concurrencywait, notify, notifyAll – used with concurrency finalizefinalize

19 Constructors and Super Java guarantees constructor call for each object Java guarantees constructor call for each object Different conventions for finalize and super Different conventions for finalize and super Compiler does not force call to super finalize Compiler does not force call to super finalize

20 Final classes and methods Restrict inheritance Restrict inheritance Final classes and methods cannot be redefinedFinal classes and methods cannot be redefined Example Example java.lang.String java.lang.String Reasons for this feature Reasons for this feature Important for securityImportant for security Programmer controls behavior of all subclasses Programmer controls behavior of all subclasses Critical because subclasses produce subtypes Critical because subclasses produce subtypes Compare to C++ virtual/non-virtualCompare to C++ virtual/non-virtual Method is “virtual” until it becomes final Method is “virtual” until it becomes final

21 Call-by-Value Parameter Passing When a method is called, When a method is called, value of argument is passed to the matching parameter, separate memory space is allocated to store this value.value of argument is passed to the matching parameter, separate memory space is allocated to store this value. This way of passing the value of arguments is called a pass-by-value This way of passing the value of arguments is called a pass-by-value Since separate memory space is allocated for each parameter during the execution of the method, Since separate memory space is allocated for each parameter during the execution of the method, the parameter is local to the method,the parameter is local to the method, changes made to the parameter will not affect the value of the corresponding argument.changes made to the parameter will not affect the value of the corresponding argument.

22 Java Types Two general kinds of types Two general kinds of types Primitive types – not objectsPrimitive types – not objects Integers, Booleans, etc Integers, Booleans, etc Reference typesReference types Classes, interfaces, arrays Classes, interfaces, arrays No syntax distinguishing Object * from Object No syntax distinguishing Object * from Object

23 Classification of Java types Reference Types Primitive Types int Shape Object[ ] Object Shape[ ] boolean … Throwable SquareSquare[ ]CircleCircle[ ] longfloatbyte Exception types user-definedarrays

24 Arrays Automatically defined Automatically defined Can have for primitive types and objects.Can have for primitive types and objects. Multi-dimensional arrays T[ ] [ ]Multi-dimensional arrays T[ ] [ ] Treated as reference type Treated as reference type An array variable is a pointer to an array, can be nullAn array variable is a pointer to an array, can be null Example: Circle[] x = new Circle[array_size]Example: Circle[] x = new Circle[array_size] Every array type is a subtype of Object[ ], Object Every array type is a subtype of Object[ ], Object Length of array is not part of its static typeLength of array is not part of its static type

25 Interface example interface Shape { public float center(); public void rotate(float degrees); public void rotate(float degrees);} interface Drawable { public void setColor(Color c); public void draw(); public void draw();} class Circle implements Shape, Drawable { // does not inherit any implementation // but must define Shape, Drawable methods // but must define Shape, Drawable methods}

26 Interfaces Flexibility Flexibility Black box design….specify input/output but, not internals.Black box design….specify input/output but, not internals.

27 Java Exceptions Similar basic functionality to C++ Similar basic functionality to C++ Constructs to throw and catch exceptionsConstructs to throw and catch exceptions Dynamic scoping of handlerDynamic scoping of handler Some differences Some differences An exception is an object from an exception classAn exception is an object from an exception class Subtyping between exception classesSubtyping between exception classes Use subtyping to match type of exception or pass it on … Use subtyping to match type of exception or pass it on … Type of method includes exceptions it can throwType of method includes exceptions it can throw

28 Exception Classes If a method may throw a checked exception, then this must be in the type of the method If a method may throw a checked exception, then this must be in the type of the method Throwable Exception Runtime Exception Error User-defined exception classes Unchecked exceptions checked exceptions

29 Try/finally blocks Exceptions are caught in try blocks Exceptions are caught in try blocks try { statements }catch (ex-type1 identifier1) { statements } catch (ex-type2 identifier2) { statements }finally { statements}

30 Keyword “this" Object can use to refer to itself. Object can use to refer to itself. Can use to refer to its variables…see example. Can use to refer to its variables…see example. class Person { int age; public void setAge(int val) { this.age = val; }... }

31 Overloaded Methods Methods can share the same name as long as Methods can share the same name as long as different number of parameters (Rule 1) ordifferent number of parameters (Rule 1) or their parameters are of different types when the number of parameters is the same (Rule 2)their parameters are of different types when the number of parameters is the same (Rule 2) public void myMethod(int x, int y) {... } public void myMethod(int x) {... } public void myMethod(double x) {... } public void myMethod(int x) {... } Rule 1 Rule 2


Download ppt "Intro to Java L. Grewe. Java history James Gosling and others at Sun, 1990 - 95 James Gosling and others at Sun, 1990 - 95 Internet application Internet."

Similar presentations


Ads by Google