1 / 50

The Java 2SE Platform

The Java 2SE Platform. Lars Degerstedt Linköping university, IDA larde@ida.liu.se. This Lecture. 1st hour – Java, the language Prelimiaries & Java 2 overview Language constructs ”Java programs” 2nd hour – Java, APIs Literature

Download Presentation

The Java 2SE Platform

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. The Java 2SE Platform Lars Degerstedt Linköping university, IDA larde@ida.liu.se

  2. This Lecture • 1st hour – Java, the language • Prelimiaries & Java 2 overview • Language constructs • ”Java programs” • 2nd hour – Java, APIs • Literature • The Java Tutorial http://java.sun.com/docs/books/tutorial

  3. Association Bone Likes Association Class Preliminaries: UML and objects Interface Class/Superclass Eater Animal size: int getFood(): Food BodyParts: List getFood(): Food Consists of Leg inherits Dog Subclass

  4. J2SE optional packages J2EE platform J2ME platform MIDP KVM J2SE optional packages … J2SE platform and SDK HotSpot JVM The Java 2 Platform and J2SE • Several parts: Language, JVM, APIs, Component models, and still growing…all packages in subplatforms. • Our main focus: J2SE = Java 2 Standard Edition

  5. The Java Language (SDK 1.4) • “Almost” pure object-oriented • Static methods/fields, e.g. the main method • Single inheritance • Interfaces and classes • Runs “interpreted” on Java Virtual Machine (JVM) everywhere, …not always true: • graphical components have problems • Different machines JVM/KVM… • Garbage collection; explicit call:java.lang.System.gc()

  6. Example Java Class …brief import java.io.*; import java.net.URL; package java.being.primates; public class Dog extends Animal implements Eater { private int size = -1; private Food food = null; public Dog(int size, Food food) { this.size = size; this.food = food; } public Food getFood() { return food; } … }

  7. Variables • Static typing (almost, see inner classes) • int zero = 0; • public String enStrang = ”nisse”; • Casting • String s = (String) anObject;

  8. Data Types • Primitive • byte,short, int, long • float double • char • Boolean • Reference • Objects • arrays

  9. Operators • Arithmetic + - * / ++, --… • Relational > , >=, <, <=, ==, != • Conditional &&, ||, !, &, |, ^ • Assignment += -= *= /= %= &= |= ^=… • Others [] .(Type)new instanceof this super • Blocks {…} • Scope is block dependent

  10. Control Flow Statements • looping while, do…while , for • Branching if…else, switch…case • Exceptions try…catch…finally,throw, throws • aborts break, continue, label:, return

  11. Java ”programs” • Executable programs are collections of classes/interfaces that: • Compiles, i.e. No dangling references • Contains a main method: static void main(String[] args) • Jar-archives optional encapsulation of compiled classes, e.g. mylib.jar

  12. Compiling/ Running Programs • javac MyClass.java -> MyClass.class • java MyClass • Starts and runs program • Start point: public class MyClass { … public static void main(String[] argv){ … } }

  13. CLASSPATH • To link in external classes • Win: • java –classpath c:\myJava;c:\jars\myjar.jar MyClass.java • Solaris: • java –classpath /home/my/myJava:/home/my/myjar.jar MyClass.java

  14. Classes • Blueprint of objects (state and behavior) • One top level class= one file • Default inheritance from java.lang.Object • Modifiers • public, protected, private • abstract, final

  15. Interfaces • Abstract Class definition • A set of methods for a class type • Class type description • Multiple views on Class • Class contract • Can also declare constants • Two uses: • Callback – making methods parameters • Polymorphism – alternative to subclasses

  16. Methods • Methods that provide behavior for Classes • In Parameters • Fixed number; use anonymous arrays for dynamic case • Return Value (return statement/type) • Single object/primitive/array • Modifiers • public, protected, private • static, final, native, synchronized

  17. Constructors • Method that initialize objects • Default constructor • Constructors are not inherited • Modifiers • public, protected, private

  18. Fields • Primitives and Classes • Must have a type • All Fields are objects in reality • Even primitives • Modifiers • public, protected, private • static, final, transient, volatile

  19. Packages & Import • Packages are namespaces for groups of Classes… • ex: java.lang • protected modifier • used to be: usable in package and for subclasses • Packages can be imported • to use Classes by short Name • e.g String vs. java.lang.String

  20. Example Class …again import java.io.*; import java.net.URL; package java.being.primates; public class Dog extends Animal implements Eater { private int size = -1; private Food food = null; public Dog(int size, Food food) { this.size = size; this.food = food; } public Food getFood() { return food; } … }

  21. Naming Conventions • Classes MyClassName • Methods myMethodName() • Variables MyClass myClass = new MyClass() • Packages java.lang, opennlp.jbrickslib.util

  22. System • java.lang.System • System.out, System.in • java.lang.RunTime • java.lang.Process, java.lang.SecurityManager • java.lang.Object • java.lang.Class, java.langClassLoader • Integer, Byte, Boolean, Char, String, StringBuffer, Double…

  23. Comments • // on liners • /* Multi linersexpanding several lines*/ • /**Javadoc comment*/

  24. Javadoc • Document generation based on @-tags and automated code extraction /** * Class description goes here. * * @version 1.82 18 Mar 1999 * @author Firstname Lastname */ public class Blah extends SomeClass {

  25. Unicode • Java character encoding • The Unicode Standard, Version 2.0, ISBN 0-201-48345-9 • A unique number for every character • no matter platform, program, language

  26. This Lecture • 1st hour – Java, the language • 2nd hour – Java, APIs • Overview of J2SE APIs • Collections • Graphics: AWT/Swing • Reflection • XML • JDBC

  27. J2SE (v1.4) APIs - Overview User Interface toolkits Swing AWT Input methods Sound Java2D Access Integration APIs RMI JDBC JNDI CORBA Core APIs XML Logging Beans Locale Pref Collections JNI Security Lang Util New I/O Network

  28. Collection/Map API • Representing and manipulating collections/maps • Collections have three parts: • Interfaces – ADT APIs • Implementations – data structures • Algorithms – polymorphism • Program with interfaces: List l = new ArrayList(); • Interoperatibility beyond vectors • Fosters software reuse • element and bulk operations: add/addAll

  29. Collection/Map: Interface Taxonomy AbstractCollection AbstractMap HashMap AbstractSet TreeMap AbstractList HashSet ArrayList TreeSet

  30. Collection/Map: Collections • Group of elements (e.g. List or Set) • Add/Remove/Iterate/Contains • Bulk operations are polymorphic, i.e. works on any Collection • Parameter for Map interface • toArray method for export

  31. Collection/Map: Lists • Positional access • Arrays.toList() method for static list view of array • ListIterator allows for manipulation during iteration • Sublist extraction

  32. Collection/Map: Maps • Collection views of keys and values • Iterators over keys, values, and tuples • Bulk op. putAll imports maps • Equals must imply hashCode for elements • Bulk op. retainAll restricts a map to a given Collection

  33. Graphics: …areComponents • AWT and Swing is based on Components and Containers • Components are placed in containers • update(), paint(), repaint() • Layout Managers • Swing is now the pushed Window Toolkit from SUN

  34. Graphics: AWT Hierarchy

  35. Graphics: AWT Event Model • Messaging across Java classes • java.awt.event (extended in javax.swing.event) • Event listener • the Observer Design pattern • Interested classes report them selves to event casting classes

  36. Graphics: AWT-Example Event import java.awt.*; import java.awt.event.*; class MyApp implements ActionListener { Button okButton = new Button(); MyApp() { // … build graphics components okButton = new Button(“OK”); okButton.addActionListener(this); // …deploy gui widget } public void actionPerformed(ActionEvent e) { System.out.println(“Hey, you pressed OK button!"); } }

  37. Graphics: Swing • Two types of entities: • atomic components and containers • More advanced Window Toolkit • but uses the AWT event model • Control-View-Model design pattern • gui-state and application-data models. Ex: Button, table resp. • Text parsing (HTML) • No native code – “lightweight” • AWT and Swing components don’t mix!

  38. Swing: Containment hierarchy ”The Containment hierarchy” OBS! Containment is a dynamic Property; not the taxonomy

  39. Swing: Code Example • publicstaticvoid main(String[] args) { • try { • UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName()); • } catch (Exception e) { } • JButton button = new JButton("I'm a Swing button!"); • button.setMnemonic(KeyEvent.VK_I); • button.addActionListener(...create an action listener...); • labelPrefix = "Number of button clicks: "; • numClicks = 0; • label = new JLabel(labelPrefix + "0 "); • JPanel pane = new JPanel(); • pane.setBorder(BorderFactory.createEmptyBorder(30, 30, 10, 30)); • pane.setLayout(new GridLayout(0, 1)); • pane.add(button); • pane.add(label); • JFrame frame = new JFrame("SwingApplication"); • frame.getContentPane().add(pane, BorderLayout.CENTER); • frame.addWindowListener(...); • frame.pack(); • frame.setVisible(true); • } Obs

  40. Swing: Containers • Containers arrange collections of visual Swing components • Top level containers: JFrame, JDialog, JApplet • Intermediate containers/Content panes: JPanel, JLayeredPanel, JInternalFrame, JScrollPane, etc.

  41. Swing: Component/ContainerTaxonomy Container AWT Window JComponent Frame AbstractButton JPanel Swing JButton JFrame

  42. AWT/Swing: Layout Managers • Objectified functionality of Container • Both AWT and Swing have managers

  43. AWT/Swing: Implementation • AWT is heavyweight have platform-specific peer classes. • Swing is lightweight uses AWT, thus only indirectly related to underlying platform. • Swing has pluggable Look and Feel • Event dispatching thread: AWT/Swing is single-threaded. • Use SwingUtilities for threads: invokeAndWait, invokeLater…

  44. Graphics: Additional Features • Drag and Drop • Internationalization • Adapting to various languages and regions without engineering changes • Accessibility • Support for People with Disabilities • Java Foundation Classes (JFC) – bean support (ready for drag and drop)

  45. XML • Java to XML • Save Java classes in XML (JAXB) • XML-Remote Procedure Call (like SOAP) • XML messaging... • Working with XML documents • XML parser • DOM navigation (eg JAXP) • XML Binding (saving Java to XML) JAXP API

  46. Reflection: Java meta-programming • Inspection of objects (both arrays and classes): • Superclasses • The Class object • Method and Field objects • Meta-creation of new objects • Meta-evaluation of methods/fields • Security and exception handling somewhat elaborate

  47. JDBC • Java Data Base Connectivity • High-level API to SQL-databases • java.sql.* • Includes network connection • Vendor specific Drivers take care of networking and DB-connections

  48. JDBC: Accessing the Database Java Client java.sql.Connection Creates Database SQL Call API Java.sql.Statement Load Driver Create a connection Create Statement and execute SQL-commands Extract Results Close connection Creates SQL Result API Java.sql.Resultset

  49. JDBC: Code Example Class.forName(”com.mysql.jdbc.Driver”).newInstance(); String url = ”jdbc:mysql://maj4.ida.liu.se:bird_database” Connection c = DriverManager.getConnection(url, "my_login", "my_password"); Statement stmt = con.createStatement(); Resultset rs = stmt.executeQuery(”SELECT * FROM species WHERE name = \”skata\”"); rs.next(); String text = rs.getString(”migration_field”); System.out.println(”Skata has migration:”+text);

  50. Java News • Java 2SE, version 1.5 • Language extensions, e.g. Parameterized types • New APIs, e.g. java.util.concurrent • Sun’s Java Desktop System • Java-based graphical desktop on top of Linux/GNOME • Java Community Process • Future enhancements of the Java Platform

More Related