+ All Categories
Home > Documents > Intro to Java L. Grewe. Java history James Gosling and others at Sun, 1990 - 95 James Gosling and...

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

Date post: 21-Dec-2015
Category:
View: 219 times
Download: 0 times
Share this document with a friend
31
Intro to Java Intro to Java L. Grewe L. Grewe
Transcript
Page 1: 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.

Intro to JavaIntro to Java

L. GreweL. Grewe

Page 2: 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.

Java historyJava history James Gosling and others at Sun, James Gosling and others at Sun,

1990 - 951990 - 95 Internet applicationInternet application

• simple language for writing programs simple language for writing programs that can be transmitted over networkthat can be transmitted over network

Page 3: 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.

Some GoalsSome Goals PortabilityPortability

• Internet-wide distribution: PC, Unix, Mac Internet-wide distribution: PC, Unix, Mac ReliabilityReliability

• Avoid program crashes and error messagesAvoid program crashes and error messages SafetySafety

• Programmer may be maliciousProgrammer may be malicious Simplicity and familiaritySimplicity and familiarity

• Appeal to average programmer; less complex than Appeal to average programmer; less complex than C++C++

Efficiency Efficiency • Important but secondaryImportant but secondary

Page 4: 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.

CharacteristicsCharacteristics

SimplicitySimplicity• 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 SafetyReliability and Safety• Run-time type and bounds checksRun-time type and bounds checks• Garbage collectionGarbage collection

Page 5: 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.

Java SystemJava System

The Java programming language The Java programming language Compiler and run-time systemCompiler 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

InteroperabilityInteroperability• Provision for “native” methodsProvision for “native” methods

Page 6: 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.

Java Release HistoryJava Release History 1995 (1.0) – First public release1995 (1.0) – First public release 1997 (1.1) – Inner classes1997 (1.1) – Inner classes 2001 (1.4) – Assertions2001 (1.4) – Assertions

• Verify programmers understanding of codeVerify programmers understanding of code 2004 (1.5) – Tiger2004 (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 62006 (1.6) – SE 6

Page 7: 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.

Enhancements since JDK 5 (= Enhancements since JDK 5 (= Java 1.5) Java 1.5)

GenericsGenerics• Polymorphism and compile-time type safety (JSR 14) Polymorphism and compile-time type safety (JSR 14)

Enhanced for LoopEnhanced for Loop• For iterating over collections and arrays (JSR 201) For iterating over collections and arrays (JSR 201)

Autoboxing/UnboxingAutoboxing/Unboxing• Automatic conversion between primitive, wrapper types (JSR 201) Automatic conversion between primitive, wrapper types (JSR 201)

Typesafe EnumsTypesafe Enums• Enumerated types with arbitrary methods and fields (JSR 201) Enumerated types with arbitrary methods and fields (JSR 201)

VarargsVarargs• Puts argument lists into an array; variable-length Puts argument lists into an array; variable-length argument lists argument lists

Static ImportStatic Import• Avoid qualifying static members with class names (JSR 201) Avoid qualifying static members with class names (JSR 201)

AnnotationsAnnotations (Metadata) (Metadata)• Enables tools to generate code from annotations (JSR 175)Enables tools to generate code from annotations (JSR 175)

Concurrency utility libraryConcurrency utility library

Page 8: 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.

Language TerminologyLanguage Terminology Class, objectClass, object Field – data member Field – data member Method - member functionMethod - member function Static members - class fields and methodsStatic members - class fields and methods this - selfthis - self Package - set of classes in shared Package - set of classes in shared

namespacenamespace Native method - method written in Native method - method written in

another language, often Canother language, often C

Page 9: 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.

Java Classes and ObjectsJava 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 lookupDynamic 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++

Page 10: 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.

Template for Class DefinitionTemplate for Class Definition

class {

}

Import StatementsImport Statements

Class CommentClass Comment

Class NameClass Name

Fields/VariablesFields/Variables

Methods(incl. Constructor)

Methods(incl. Constructor)

Page 11: 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.

Point ClassPoint Classclass Point {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;} Point(int xval) {x = xval;} // //

constructorconstructor};};

Page 12: 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.

Object initializationObject initialization Java guarantees constructor call for Java guarantees constructor call for

each objecteach object• Memory allocatedMemory allocated• Constructor called to initialize memoryConstructor called to initialize memory• Some interesting issues related to inheritance Some interesting issues related to inheritance

Page 13: 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.

Garbage Collection and FinalizeGarbage Collection and Finalize

Objects are garbage collectedObjects are garbage collected• No explicit No explicit freefree• Avoids dangling pointers and resulting type errorsAvoids dangling pointers and resulting type errors

ProblemProblem• What if object has opened file or?What if object has opened file or?

SolutionSolution• finalizefinalize method, called by the garbage collector method, called by the garbage collector

Before space is reclaimed, or when virtual Before space is reclaimed, or when virtual machine exitsmachine exits

Page 14: 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.

Encapsulation and packagesEncapsulation and packages Every field, method Every field, method

belongs to a classbelongs to a class Every class is part Every class is part

of some packageof some package• Can be unnamed Can be unnamed

default packagedefault package• File declares which File declares which

package code package code belongs tobelongs to

package

classfield

method

package

classfield

method

Page 15: 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.

AccessAccess Four access distinctionsFour access distinctions

• public, private, protected, packagepublic, private, protected, package Method can refer toMethod 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 Visibility determined by files system, etc. (outside language)language)

Qualified names Qualified names (or use import)(or use import)• java.lang.String.substring()java.lang.String.substring()

package classmetho

d

Page 16: 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.

InheritanceInheritance Similar to Smalltalk, C++Similar to Smalltalk, C++ Subclass inherits from superclassSubclass inherits from superclass

• Single inheritance only (but Java Single inheritance only (but Java has interfaces)has interfaces)

Page 17: 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.

Example subclassExample subclassclass ColorPoint class ColorPoint extendsextends Point { 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); super(xval); // call Point constructor// call Point constructor

c = cval;c = cval; } } // initialize ColorPoint field // initialize ColorPoint field

};};

Page 18: 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.

Class Class ObjectObject Every class extends another classEvery class extends another class

• Superclass is Superclass is ObjectObject if no other class namedif no other class named Methods of classMethods of class Object Object

• GetClass – return the Class object representing class of the GetClass – return the Class object representing class of the object 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)• hashCode hashCode • 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

Page 19: 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.

Constructors and SuperConstructors and Super Java guarantees constructor call for each Java guarantees constructor call for each

objectobject Different conventions for finalize and superDifferent conventions for finalize and super

Compiler does not force call to super finalizeCompiler does not force call to super finalize

Page 20: 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.

Final classes and methodsFinal classes and methods

Restrict inheritanceRestrict inheritance• Final classes and methods cannot be redefinedFinal classes and methods cannot be redefined

ExampleExample java.lang.Stringjava.lang.String

Reasons for this featureReasons for this feature• Important for securityImportant for security

Programmer controls behavior of all subclassesProgrammer controls behavior of all subclasses Critical because subclasses produce subtypesCritical because subclasses produce subtypes

• Compare to C++ virtual/non-virtualCompare to C++ virtual/non-virtual Method is “virtual” until it becomes finalMethod is “virtual” until it becomes final

Page 21: 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.

Call-by-Value Parameter Call-by-Value Parameter PassingPassing

When a method is called, When a method is called, • value of argument is passed to the matching parameter, value of argument is passed to the matching parameter,

separate memory space is allocated to store this value. separate memory space is allocated to store this value.

This way of passing the value of This way of passing the value of arguments is called a arguments is called a pass-by-valuepass-by-value

Since separate memory space is allocated Since separate memory space is allocated for each parameter during the execution for each parameter during the execution of the method, 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 changes made to the parameter will not affect the value

of the corresponding argument.of the corresponding argument.

Page 22: 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.

Java TypesJava Types Two general kinds of typesTwo general kinds of types

• Primitive types – Primitive types – notnot objects objects Integers, Booleans, etcIntegers, Booleans, etc

• Reference typesReference types Classes, interfaces, arraysClasses, interfaces, arrays No syntax distinguishing Object * from ObjectNo syntax distinguishing Object * from Object

Page 23: 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.

Classification of Java typesClassification of Java typesReference Types

Primitive Types

int

Shape

Object[ ]

Object

Shape[ ]

boolean …

Throwable

Square Square[ ]Circle Circle[ ]

longfloatbyte

Exception types

user-defined arrays

Page 24: 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.

ArraysArrays

Automatically definedAutomatically 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 typeTreated as reference type• An array variable is a pointer to an array, can be An array variable is a pointer to an array, can be

nullnull• Example: Example: Circle[] x = new Circle[array_size]Circle[] x = new Circle[array_size]

Every array type is a subtype of Object[ Every array type is a subtype of Object[ ], Object], Object• Length of array is not part of its static typeLength of array is not part of its static type

Page 25: 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.

Interface exampleInterface exampleinterface Shape {interface Shape {

public float center();public float center(); public void rotate(float degrees);public void rotate(float degrees);}}interface Drawable {interface Drawable {

public void setColor(Color c);public void setColor(Color c); public void draw();public void draw();}}class Circleclass Circle implements implements Shape, Drawable { Shape, Drawable {

// does not inherit any implementation// does not inherit any implementation // but must define Shape, Drawable methods// but must define Shape, Drawable methods }}

Page 26: 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.

InterfacesInterfaces

FlexibilityFlexibility• Black box design….specify input/output Black box design….specify input/output

but, not internals.but, not internals.

Page 27: 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.

Java ExceptionsJava Exceptions Similar basic functionality to C++ Similar basic functionality to C++

• Constructs to Constructs to throwthrow and and catchcatch exceptions exceptions• Dynamic scoping of handlerDynamic scoping of handler

Some differencesSome 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 Use subtyping to match type of exception or pass it on … it on …

• Type of method includes exceptions it can throwType of method includes exceptions it can throw

Page 28: 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.

Exception ClassesException Classes

If a method may throw a checked exception, then If a method may throw a checked exception, then this must be in the type of the methodthis must be in the type of the method

Throwable

Exception RuntimeException

Error

User-definedexception classes

Unchecked exceptions

checked exceptions

Page 29: 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.

Try/finally blocksTry/finally blocks Exceptions are caught in try blocksExceptions are caught in try blocks

try {try {

statementsstatements

}} catch (ex-type1 identifier1) {catch (ex-type1 identifier1) {

statementsstatements

} catch (ex-type2 identifier2) {} catch (ex-type2 identifier2) {

statementsstatements

}} finally {finally {

statementsstatements

}}

Page 30: 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.

Keyword “this"Keyword “this"

Object can use to refer to itself.Object can use to refer to itself. Can use to refer to its variables…see Can use to refer to its variables…see

example.example.

class Person {

int age;

public void setAge(int val) { this.age = val;}. . .

}

Page 31: 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.

Overloaded MethodsOverloaded Methods Methods can share the same name as long asMethods can share the same name as long as

• different number of parameters (different number of parameters (Rule 1)Rule 1) oror• their parameters are of different types when the number their parameters are of different types when the number

of parameters is the same (of parameters is the same (Rule 2Rule 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


Recommended