500 likes | 682 Views
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
E N D
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 • The Java Tutorial http://java.sun.com/docs/books/tutorial
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
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
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()
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; } … }
Variables • Static typing (almost, see inner classes) • int zero = 0; • public String enStrang = ”nisse”; • Casting • String s = (String) anObject;
Data Types • Primitive • byte,short, int, long • float double • char • Boolean • Reference • Objects • arrays
Operators • Arithmetic + - * / ++, --… • Relational > , >=, <, <=, ==, != • Conditional &&, ||, !, &, |, ^ • Assignment += -= *= /= %= &= |= ^=… • Others [] .(Type)new instanceof this super • Blocks {…} • Scope is block dependent
Control Flow Statements • looping while, do…while , for • Branching if…else, switch…case • Exceptions try…catch…finally,throw, throws • aborts break, continue, label:, return
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
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){ … } }
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
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
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
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
Constructors • Method that initialize objects • Default constructor • Constructors are not inherited • Modifiers • public, protected, private
Fields • Primitives and Classes • Must have a type • All Fields are objects in reality • Even primitives • Modifiers • public, protected, private • static, final, transient, volatile
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
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; } … }
Naming Conventions • Classes MyClassName • Methods myMethodName() • Variables MyClass myClass = new MyClass() • Packages java.lang, opennlp.jbrickslib.util
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…
Comments • // on liners • /* Multi linersexpanding several lines*/ • /**Javadoc comment*/
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 {
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
This Lecture • 1st hour – Java, the language • 2nd hour – Java, APIs • Overview of J2SE APIs • Collections • Graphics: AWT/Swing • Reflection • XML • JDBC
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
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
Collection/Map: Interface Taxonomy AbstractCollection AbstractMap HashMap AbstractSet TreeMap AbstractList HashSet ArrayList TreeSet
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
Collection/Map: Lists • Positional access • Arrays.toList() method for static list view of array • ListIterator allows for manipulation during iteration • Sublist extraction
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
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
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
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!"); } }
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!
Swing: Containment hierarchy ”The Containment hierarchy” OBS! Containment is a dynamic Property; not the taxonomy
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
Swing: Containers • Containers arrange collections of visual Swing components • Top level containers: JFrame, JDialog, JApplet • Intermediate containers/Content panes: JPanel, JLayeredPanel, JInternalFrame, JScrollPane, etc.
Swing: Component/ContainerTaxonomy Container AWT Window JComponent Frame AbstractButton JPanel Swing JButton JFrame
AWT/Swing: Layout Managers • Objectified functionality of Container • Both AWT and Swing have managers
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…
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)
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
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
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
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
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);
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