intro to java l. grewe. java history james gosling and others at sun, 1990 - 95 james gosling and...
Post on 21-Dec-2015
222 views
TRANSCRIPT
Intro to JavaIntro to Java
L. GreweL. Grewe
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
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
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
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
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
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
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
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++
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)
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};};
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
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
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
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
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)
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
};};
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
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
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
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.
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
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
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
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 }}
InterfacesInterfaces
FlexibilityFlexibility• Black box design….specify input/output Black box design….specify input/output
but, not internals.but, not internals.
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
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
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
}}
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;}. . .
}
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