1 / 67

Java Overview

Java Overview. About me. Peter Kriens Work as a consultant (mainly for for ERICSSON) Finnasandsvagen 22 43933 Onsala, Sweden +46 705950899 Peter.Kriens@aQute.se. History. 1990 SUN starts crash team under Patrick Naughton Carte blanche to clean up the software mess at SUN

Télécharger la présentation

Java Overview

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Java Overview

  2. About me • Peter Kriens • Work as a consultant (mainly for for ERICSSON) • Finnasandsvagen 22 • 43933 Onsala, Sweden • +46 705950899 • Peter.Kriens@aQute.se

  3. History • 1990 SUN starts crash team under Patrick Naughton • Carte blanche to clean up the software mess at SUN • Gosling created OAK for embedded devices (!) • Products all failed • 1993 Mosaic, the first web browser was born • Somebody realized the combination: Applets • Language became the product

  4. History • 1996 JDK 1.0 released • Focused on Applets, lousy graphics • 8 packages, 4Mb download • 1997 JDK 1.1 released • Better graphics, reflection, security (try), beans, RMI, ZIP files • 22 Packages, 9 Mb download

  5. History • 1999 JDK 1.2 SE released • Lightweight UI (!), collections, security (again), JAR files, Native interface change… • 59 packages, 20 Mb download • 2000 JDK 1.3 SE in beta • Improvements ... • 77 packages (so far), 25 Mb download

  6. Quick Tour: Hello World • Getting started • Content of file: HelloWorld.java • /** * Small hello world example class. * */public class HelloWorld { public static void main( String args[] ) { System.out.println( "Hello world" + (args.length >= 1 ? args[0] : "whoever") ); }} • javac HelloWorld.java • java HelloWorld peterHello world peter • That is all ...

  7. Quick Tour: Objects • Creating a class • Content of file: Point.java • /** * A Simple point class. */public class Point { double _x; // Instance variable double _y; public Point() { this(0,0); } public Point( double x, double y ) { _x=x; _y=y; } public double getX() { return _x; } public double getY() { return _y; } public double getLength() { return Math.sqrt( getX()*getX() + getY() * getY() ); } public Point translate( Point t ) { return new Point(getX() + t.getX(), getY() + t.getY() );}}

  8. Quick Tour: Not to be an Object • Not all variables are objects like in Smalltalk • int, char, boolean, long, double, float, byte are <primitive> types. • Each primitive type is represented by a class in java.lang • public class HelloWorld { public static void main( String args[] ) { int length = args.length; Point p = new Point( length, length ); }}

  9. Quick Tour: Inner class • Everything had to be a class. Callbacks require their own class • Too cumbersome to specify in other file, so special syntax was wrought (ugly!): • public static void main( String args[] ) { Point p = new Point() { public double getX() { return super.getX() * 2; } };

  10. Quick Tour: Garbage Collection • Java cleans up after you • /* GC */...Point p = new Point();p = p.translate( new Point(10,10) );... • Previous code creates 3 new objects • No need for destructor. No need for delete

  11. Quick Tour: Inheritance • Classes can be extended • /* Extending point class */public class Point3 extends Point { double _z; public Point3() { _z=0; super(0,0); } public double getZ() { return _z; } public double getLength() { return Math.sqrt( getX()*getX() + getY()*getY() + getZ() * getZ() ); } ...} • Only use it for an "is-a" relationship • Powerful but easy to overdo

  12. Quick Tour: Inheritance • Single inheritance only • All classes inherit from class Object • A Class is a an instance of class Class • So the class Class is an instance of Class (!) • Class objects can be used as normal objects • Reflection • ClassLoaders • "super" keyword to access super class

  13. Quick Tour: Interfaces • Used for specifications • /* Interfaces */public interface Compare { public int compare( Compare t );}class CPoint extends Point implements Compare { public int compare( Compare t ) { Point tt = (Point) t; return getLength() - t.getLength(); }} • Decouples using from implementation • Very popular with specifications

  14. interface Quick Tour: Interfaces public interface Log { public void log(String s);} client uses Log public class SimpleLog { public void log(String s) { System.out.println( s ); }} implements Simple Log IBM Log Motorola Log

  15. Quick Tour: Exceptions • Exceptions are used to separate normal flow of program from error cases • Runtime exceptions: • public class HelloWorld { public static void main( String args[] ) { System.out.println( "Hello world" + args[0] ); }}

  16. Quick Tour: Exceptions • Checked exceptions: • public class HelloWorld { public static void main(String args[]) throws IOException { FileOutputStream out = new FileOutputStream( "temp" ); out.write( args[0].getBytes() ); out.close(); }} • Exceptions can be very messy

  17. Quick Tour: Exceptions • Handling exceptions: • public class HelloWorld { public static void main( String args[] ) { FileOutputStream out; try { out = new FileOutputStream( "temp" ); out.write( args[0].getBytes() ); out.close(); } catch( IOException e ) { System.out.println( "Exception " + e ); e.printStackTrace(); } finally { try { out.close(); } catch(Exception ee) {} } }} • Never ignore exceptions: catch(...) {} • Easy to overdo exceptions

  18. Quick Tour: Packages • Name spaces for Java • package = add a class to a package • import = use classes from a package • Encapsulate a number of related classes • Used for access control • Content of file: ../se/aQute/plane/Point.java • package se.aQute. plane;import se.aQute.basictest.*;public class Point { double _x; double _y; public Point() { clear(); } ...}

  19. Quick Tour: Equality • Equal and identical are different concepts • Identity check is == • Class Object has method equals(Object o) method that is identity • 3 == 3; // YES • "three" == new String("three"); // NO • "three".equals( new String("three") ); // YES • Classes can override equals(Object o) for their semantics • Watch hashCode() when overriding equals() !!!

  20. Quick Tour: toString() • toString() is a useful method for debugging • Each object inherits a default implementation from Object • Overriding can be very, very useful during debugging • public class Point { . . . public String toString() { return getX() + "," + getY(); } . . .}

  21. The Java VM • Java is compiled to byte codes • Byte codes are interpreted by the VM File: HelloWorld.java public class HelloWorld { public static void main( String args[] ) { System.out.println( "Hello world" ); } } File: HelloWorld.class javac compiler 0xCA 0xFE 0xBA 0xBE 0x01 0xF7 0x76 0x41 0x23 . . . rt.jar or classes.zip java VM Hello world

  22. Native code interface • Native code interface through JNI • Native interface defined in Java class • class Native { int var; public native int foo();} • Translated via javah into C header file • #include <native.h>typedef struct ClassNative { long var; } ClassNative;HandleTo(Native);extern long Native_foo(struct HNative *);

  23. The Java VM: The good news • Portable format allows execution on many different computer types • Hundreds of VMs available from different vendors • Optimized for certain applications • Inherently safe

  24. The Java VM: The bad news • Interpretation requires CPU cycles • Instruction set not optimized for target machines • Byte format is rather verbose

  25. Is Java Cool? • Nothing particularly innovative • Portable object code from Pascal (P-code!) • Syntax from C++ • Object model from Smalltalk • Garbage Collection from Lisp • Reasons for success: • People were getting fed up with C++ • Java looked much simpler • Applets kick started it (but no longer drive it)

  26. The runtime library • The runtime library is Java's best asset • Single implementation of common code • Some implementations are pretty bad (AWT!) • Library has grown very hard • From 8 packages to 77 packages! • Need for profiles • There is an amazing amount of code to be found on the net

  27. The runtime library: java.lang • Basic package which is always included • Contains primitive type classes for Boolean, Integer, Double, Float, Byte, Character, Void • number <-> string conversions • number <-> number conversions • Max/Min values • Used in reflection

  28. The runtime library: java.lang • Process, Runtime and System for access to system resources • Running of external processes and linking of external libraries • Debugging • Memory interface • Time • System properties • Utiltity functions like arraycopy

  29. The runtime library: java.lang • Thread, ThreadGroup for threads • A Thread is like an internal process • Run multiple threads at the same time • Combine threads in a group for security control • Monitors are used to manage shared resources • Math = Math library • Contains mathematical routines • sqrt, cos, sin, log, ln ...

  30. The runtime library: java.lang • Throwable • Base class for Exceptions and Error • SecurityManager for security • Performs security checks (when installed) • Access to call stack

  31. The runtime library: java.lang • String • Unicode! • 16 bit char = 65536 possible characters • Functions • String can be concatenated with + • System.out.println( "File : " + file + " : " + exception ); • substring, indexOf, trimming • Conversion from number to String • Symbols (unique value with intern() )

  32. The runtime library: java.lang • StringBuffer • Used to concatenate strings • Expensive: • String concat = "";for ( int i=0; i<10; i++ ) concat = concat + i; • Less Expensive • StringBuffer sb = new StringBuffer();for ( int i=0; i<10; i++ ) sb.append( "" + i );String concat = sb.toString();

  33. The runtime library: java.io • Streams are used for byte access to files • Readers/Writers are used for Unicode access • Streams, Readers, Writers can be used as pipes • Buffering • Data access (e.g. getInt(), getShort() ) • Between threads (PipeXXXXX) • Conversion from stream to reader/writer • ObjectStreams

  34. The runtime library: java.net • Access to the net (TCP/IP) • InetAddress • Stream connections: Socket, ServerSocket • Extendable: SocketImplFactory • URL, URLConnection • Extendable: URLStreamHandlerFactory • Datagrams • Unicast/Multicast

  35. The runtime library: java.util • Useful classes • Collections: Vector, Hashtable, BitSet, Properties, Stack, Enumeration, Map, Array, Iterator • Time: Date, Calendars, TimeZones • Locale: Locale, ResourceBundles • Random • Observable • StringTokenizer • EventObject, EventListener

  36. The runtime library: other • java.rmi • Remote method invocation support • java.math • Big Integer (unlimited digits) for private/public key calculations

  37. The runtime library: more other • java.security • Classes for certificates, principals, permissions • java.sql • Access support to SQL databases • java.text • Support for language independent messages • java.util.zip • Access to zip files which are the preferred delivery vehicle for java applications.

  38. The runtime library: more other • java.util.jar • Access to jar files and their manifest • java.lang.reflect • Access to objects in runtime via reflection on their interfaces • java.beans • Support for Java beans

  39. The runtime libraries: GUI • Original AWT in 1.0 was … well, awful • JDK 1.1 at start 1997 improved significantly • Netscape released lightweight GUI called IFC at that time • SUN decided to develop their own lightweight GUI at the end of 1997 • Netscape joined them SUN team and stopped support for IFC

  40. GUI: AWT • Uses peer model • A widget controls a native widget • Supports "native look and feel" • Event model: • first based on single dispatching method handleEvent • Today based on listeners • Layout managers • LightWeight components

  41. GUI: AWT looks

  42. GUI: IFC • Derived from NeXT, adopted by Netscape • Lightweight components • Very clean code, small, reliable and included in Netscape Communicator • Internal windows, drag & drop • Event handling via strings • Powerful GUI builder called Constructor • Available (including source) but not maintained

  43. GUI: IFC example, full control

  44. GUI: JFC • Derived from IFC (same people [@ start]) • Lightweight components, listeners • JButton top = new JButton("Top");top.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { System.out.println("top"); }} ); • Compare Smalltalk, there it would be:Button top = Button new: 'top'.top action: [ Transcript print: 'top' ]. • HUGE • Based on Model-View paradigm & Pluggable UI • Easier to use than it looks

  45. GUI: JFC complexity, the button L&F ... Button UI Abstract Button Button Model Default Button Model JButton JToggle Button JMenu Item JRadio Button JCheck Box JCheckBox MenuItem JMenu JRadioButton MenuItem

  46. JFC: The good and changing looks

  47. Components: Beans • Components are wrapped objects • Access via reflection • Allows runtime composition of systems (via end users?): Visual Programming • Properties can be set via strings Bean Methods Events Properties

  48. Java Beans • Events follow the listener model • SomeBean bean = new SomeBean();bean.addTickEventListener(new TickEventListener() { public void tick(TickEvent e) { System.out.println("tick");}}); • Properties are defined via methods that start with get/set • E.g. property "tickCount"public class SomeBean { public long getTickCount() { … } public void setTickCount() { … }} • Bean programmer can override defaults with an Introspector

  49. The Bean Box

  50. Enterprise Java Beans • SUN's attempt to enter the enterprise computing market • Mainframe connectivity • Application Servers • Message Queues • Transactions EJB client

More Related