CSE 502 Au07 - PowerPoint PPT Presentation

Loading...

PPT – CSE 502 Au07 PowerPoint presentation | free to view - id: 14d8c-MTJkN



Loading


The Adobe Flash plugin is needed to view this content

Get the plugin now

View by Category
About This Presentation
Title:

CSE 502 Au07

Description:

Advanced Java ... Applets to run in browser, Java JumpStart. Java2 Enterprise Edition (J2EE) ... Core Java(TM) 2, Volume I--Fundamentals (7th Edition) ... – PowerPoint PPT presentation

Number of Views:245
Avg rating:3.0/5.0
Slides: 199
Provided by: bobma5
Category:
Tags: cse | au07 | java

less

Write a Comment
User Comments (0)
Transcript and Presenter's Notes

Title: CSE 502 Au07


1
CSE 502 Au07
  • Object-Oriented Programming with Java Eclipse
  • Dr. Bob Mathis
  • http//www.cse.ohio-state.edu/bmathis
  • mailtobmathis_at_cse.ohio-state.edu?subject502
  • Mon, Wed 430p 548p, DL 317, schedule
  • Graduate level course
  • Higher level approach to program development
  • Diversity in individual goals
  • Group discussion and reporting
  • Ill be glad to explain whatever I can

2
NEW UNIVERSITY EMERGENCY NOTIFICATION PLAN
  • Ohio State has a number of ways to communicate
    with faculty, staff, students and parents in the
    event of an urgent situation. These include a
    variety of notification vehicles such as WOSU AM,
    OSU Today e-mail, the Ohio State Web site, and
    local media outlets. New this year, the
    university has created a text message alert
    system for the public to stay informed of
    potential emergencies. Faculty, students, staff,
    and parents are encouraged to register their cell
    phone numbers with the OSU Department of Public
    Safety. To learn more and to register, go to
    www.buckeyealert.osu.edu

3
Java App for Everything?
  • Even Dilbert Friday, September 7, 2007

4
CSE 502 Expectations Requirements
  • Graduate level course/seminar
  • High school structured, paced, everybody
    together, supervision
  • College more on your own
  • Graduate School self-directed and motivated
  • Expect all A grades
  • Expect participation
  • Projects relevant to your field
  • Project something useful from this course

5
Ways of Teaching Learning
  • Different ways of presenting information
  • Historical evolution of ideas (Hebrew)
  • Hierarchical, categorized topics (Greek)
  • Intertwined stories / examples (Arabic)
  • Jumping from topic to topic
  • Trying to respond to needs and questions
  • Youre majoring in something other than computer
    science, but want to learn as much as possible
    about computer programming

6
How to Program in Java
  • How to Program
  • Object-oriented programming, analysis design
  • Tools, approaches, patterns
  • In the background of every topic
  • Tactics, strategy, philosophy
  • Java
  • Modern programming language (1995? )
  • Java6 almost a year old
  • Sun (IBM, others) have worked to significantly
    improve the language and its implementation

7
CSE 502 Java
  • Basic Java (mostly personal applications)
  • Java6 Eclipse
  • Object-oriented programming patterns
  • Advanced Java
  • Distributed applications, concurrency, GUI, data
    bases, assertions, testing, logging, profiling,
    native programs, etc.
  • Applets to run in browser, Java JumpStart
  • Java2 Enterprise Edition (J2EE)
  • Running applications on server, specialized

8
CSE 502 Resources on the Net
  • All CSE 502 resources and communications on web
    and via e-mail
  • http//www.cse.ohio-state.edu/bmathis
  • mailtobmathis_at_cse.ohio-state.edu?subject502
  • Java programming, software engineering
  • http//java.sun.com
  • http//www.redbooks.ibm.com/
  • Safari through OSU Library
  • Computer set-ups of some others

9
General Notices / Disclaimers
  • This course may contain information that is
    privileged, proprietary and confidential and/or
    exempt from disclosure under applicable law.
    This transmission is intended solely for the
    individual or entity designated above. If you
    are not the intended recipient, you should
    understand that any distribution, copying, or use
    of the information contained in this transmission
    by anyone other than the intended recipient is
    unauthorized and strictly prohibited. If you
    have received this course material in error,
    please immediately notify the sender and destroy
    all copies which you may have of this
    communication.
  • The instructor has taken care in the preparation
    of this course material, but makes no expressed
    or implied warranty of any kind and assumes no
    responsibility for errors or omissions. No
    liability is assumed for incidental or
    consequential damages in conjunction with or
    arising out of the use of the information or
    programs contained herein.
  • Historical performance is no guarantee of future
    returns.
  • Legal information is not the same as legal
    advice.
  • The instructor
  • has prepared the content of this course
    responsibly and carefully, but disclaims all
    warranties, express or implied, as to the
    accuracy of the information contained in any of
    the materials on this course or on other linked
    websites or on any subsequent links. This
    includes but is not by way of limitation
  • any implied warranties of merchantability and
    fitness for a particular purpose
  • any liability for damage to your computer
    hardware, data, information, materials and
    business resulting from the information or the
    lack of information available
  • any errors, omissions, or inaccuracies in the
    information
  • any decision made or action taken or not taken in
    reliance upon the information
  • makes no warranty as to the content, accuracy,
    timeliness or completeness of the information or
    that the information may be relied upon for any
    reason and bears no responsibility for the
    accuracy, content or legality of any linked site
    or for that of any subsequent links.
  • shall not be liable for any losses or damages
    (including without limitation consequential loss
    or damage) whatsoever from the use of, or
    reliance on, the information in this course, or
    from the use of the material generally. Any links
    to other websites do not constitute an
    endorsement or an approval by the instructor of
    any products, services, policies or opinions of
    the organization or individual.
  • Neither the instructor, nor The Ohio State
    University, nor the Department of Computer
    Science and Engineering, nor any of their
    employees, students, or associates, make any
    warranty, express or implied, including
    warranties of merchantability and fitness for a
    particular purpose, or assume any legal liability
    for the accuracy, completeness, or usefulness of
    any information from this server or the links to
    other servers.
  • License and site access
  • The instructor grants you a limited license to
    access and make personal use of this site. This
    site and any portion hereof may not be
    reproduced, duplicated, copied, downloaded, sold,
    resold, visited, or otherwise exploited for any
    commercial purpose without the express written
    consent of the instructor.
  • Forward-looking statements
  • This web site includes forward-looking
    statements, which are based on certain
    assumptions and reflect the instructors current
    expectations. These forward-looking statements
    are subject to a number of risks and
    uncertainties that could cause actual results or
    events to differ materially from current
    expectations. Some of the factors that could
    cause actual results to differ materially from
    current expectations are actions of our
    competitors failure of our significant
    investments in technology to increase our
    revenues or decrease our operating costs failure
    to fully derive anticipated benefits from our
    acquisitions failure to develop additional
    products and services to meet our customers'
    needs, attract new customers or expand into new
    geographic markets failure to meet the special
    challenges involved in expansion of our
    operations outside North America failure to
    recruit and retain high quality management and
    key employees consolidation of our customers
    increased self-sufficiency of our customers
    increased accessibility to free or relatively
    inexpensive information sources failure to
    maintain the availability of information obtained
    through licensing arrangements and changes in the
    terms of our licensing arrangements changes in
    the general global economic conditions
    inadequate protection of our intellectual
    property rights an increase in our effective
    income tax rate impairment loss affecting our
    goodwill and identifiable intangible assets
    recorded on our balance sheet and failures or
    disruptions of our electronic delivery systems or
    the internet. The instructor disclaims any
    intention or obligation to update or revise any
    forward-looking statements, whether as a result
    of new information, future events or otherwise.
  • Disclaimer of warranties and limitation of
    liability
  • This site is provided by the instructor on an "as
    is" and "as available" basis. The instructor
    makes no representations or warranties of any
    kind, express or implied, as to the operation of
    this site, or the information, content or
    materials included on this site. You expressly
    agree that your use of this site is at your sole
    risk.

10
Al Gore, May 2007, Time Magazine
11
CSE 502 Mathis, Summer 2007
12
Bob Mathis
  • Upper Arlington High School (Jack Nicklaus,
    Beverly DAngelo, Simon Fraser?) (George Smoot,
    2006 Noble Prize in Physics, class of 1962)
  • 1959 7th grade 1969 Ph.D. and on faculty of
    Ohio State
  • Full-time consulting practice in
    computing part-time lecturer OSU / CSE
  • Previously head of Ada project for DoD, Contel
    Technology Center, chairman of standards
    committees, teaching at other universities, etc.

13
Pithecanthropus
14
CSE 502 Textbook Recommended
OReilly, 2005 ISBN-10 0596008732 ISBN-13
978-0596008734 List Price44.95 Price29.67 Yo
u Save15.28 (34) Amazon as of
2007.05.22 http//www.oreilly.com/
catalog/learnjava3/ Locally scanned pages
15
Previous 502 Textbook
Core Java(TM) 2, Volume I--Fundamentals (7th
Edition) by Cay Horstmann Gary Cornell (P-H,
2004) Core Java(TM) 2, Volume IIAdvanced
Features http//horstmann.com/corejava.html
16
Other Java Books
Java In A Nutshell, 5th Edition by David
Flanagan, OReilly, 2005
17
Other Good Java Books
18
Java Web Sites to Visit
  • Sun http//java.sun.com
  • EclipseEclipse http//www.eclipse.org
  • Safari through OSU library
  • Learning Java textbook CD web-site http//examples
    .oreilly.com/learnjava3/CD-ROM/

19
Java on the Web
  • Download Java SDK (with/without NetBeans)
  • Java tutorials (Sun Java site and others)
  • Eclipse (MyEclipseIDE.com)
  • Java book sites
  • Café au lait
  • Java Lobby
  • OReilly site
  • Lots of Other Good Java Sites

20
Java in Your Cup
21
Java History
  • FORTRAN
  • ALGOL (1960) BASIC
  • BCPL
  • Pascal C Visual Basic
  • C
  • Ada (1979) Internet
  • Java (1995) Windows95
  • Ada (2nd rev) Java6 Multi-core CPU

22
March of Progress? - Horstmann
  • 1980 C 
  • printf("10.2f", x)
  • 1988 C
  • cout showpoint
  • 1996 Java
  • java.text.NumberFormat formatter
    java.text.NumberFormat.getNumberInstance() format
    ter.setMinimumFractionDigits(2) formatter.setMaxi
    mumFractionDigits(2) String s
    formatter.format(x) for (int i s.length() i
    10 i) System.out.print(' ') System.out.print(s
    )
  • 2004 Java
  • System.out.printf("10.2f", x)

23
Why Java
  • C syntax, but C not a subset, object-oriented
    from the beginning
  • Intended for network programming
  • Multi-platform portability
  • GUI independent of Microsoft Windows
  • Security, concurrency, databases
  • Continually improved over last dozen years

24
Programming in Java6 is Different
  • Java significant improvements
  • Improved execution
  • Improved language features (tasking, generics)
  • Improved program development environments
  • CSE 502 is about the future of programming
  • Where profession is going
  • Programming is different from what you may have
    learned and almost certainly different than what
    your professors learned years ago.

25
Developing Java Programs
  • Text editors automating keypunches
  • Search replace, managing files
  • Some improvement over the old way
  • Integrated Development Environments
  • Microsoft Visual Studio (C and VB)
  • Sun Studio (Net Beans)
  • Eclipse (MyEclipse)
  • Combination of writing and tool assistance

26
Java Development Environments
  • Eclipse (in CSE labs)
  • MyEclipse (version Mathis uses)
  • NetBeans (from Sun)
  • IntelliJ IDEA (popular with Java speakers) (door
    prize at local Java Users Group)
  • BlueJ (high school advanced test)
  • JBuilder, Visual Age for Java, Visual Café (old
    previous products Borland, IBM, Symantec)
  • Text editors (some with language assistance)

27
Initial Eclipse Demo
  • Download, unzip, start Eclipse
  • Pick convenient (backup-able) workspace
  • New project, package, class (with main)
  • How much typing versus knowing about Java
    letting the development environment help
  • For you to try later
  • Sum integers 1 through 10 and print answer (note
    n(n1)/2 55 when n10)

28
Screen Shot - Eclipse Welcome
29
Screen Shot - Eclipse Workbench
30
Learning Java 3rd, Chap 1a
  • Textbook
  • Scanned pages
  • Safari (through OSU Libraries)
  • Chapter 1
  • A Modern Language (reread as you learn more)
  • Enter Java (Javas Origins, Growing Up)
  • A Virtual Machine (Just In Time Compilation)
  • Java Compared with Other Languages
  • Safety of Design (Simplify, Simplify, Simplify…,
    Type Safety and Method Binding, Incremental
    Development, Dynamic Memory Management, Error
    Handling, Threads, Scalability)

31
Learning Java 3rd, Chap 1b
  • Safety of Implementation (The Verifier, Class
    Loaders, Security Managers)
  • Application and User-Level Security (Signing
    Classes)
  • Java and the Web (Applets, New Kinds of Media,
    New Software Development Models)
  • Java as a General Application Language
  • A Java Road Map (The Past Java 1.0 Java
    1.4, The Present Java 5.0 Dec 2006 Java6, The
    Future, Availability)

32
Learning Java 3rd, Appx. A
  • The Eclipse IDE
  • Basics havent changed much, version 3.x
  • Lots of helps
  • Outlines, program structure
  • Quick fix other options and prompts
  • Refactoring (renaming)
  • Source formatting
  • Programming with a text editor is little more
    than automating use of punched cards
  • Even with syntax recognition coloring features

33
Learning Java 3rd, Chap 2a
  • A First Application
  • Java Tools and Environment Eclipse for us
  • HelloJava (initial source on next slide)
  • Classes
  • The main() Method
  • Classes and Objects
  • Variables and Class Types
  • HelloComponent
  • Inheritance
  • The JComponent Class
  • Relationships and Finger Pointing
  • Package and Imports
  • The paintComponent() Method

34
HelloJava (Multiple Versions)
  • public class HelloJava
  • public static void main( String args )
  • System.out.println("Hello, Java!")
  • // but hes not content with that
  • // scanned pages, p. 30
  • // look at this in Eclipse

35
Learning Java 3rd, Chap 2b
  • HelloJava2 The Sequel (Instance Variables,
    Constructors, Events, The repaint() Method,
    Interfaces)
  • HelloJava3 The Button Strikes! (Method
    Overloading, Components, Containers, Layout,
    Subclassing and Subtypes, More Events and
    Interfaces, Color Commentary, Static Members,
    Arrays, Our Color Methods)
  • HelloJava4 Netscapes Revenge (Threads, The
    Thread Class, The Runnable Interface, Starting
    the Thread, Running Code in the Thread,
    Exceptions, Synchronization)
  • Troubleshooting
  • Compilation (javac) Errors, Runtime (java)
    Errors, Java Version Problems, The
    getContentPane() Error

36
Other Details About Running Java
  • Almost a review to make sure covered
  • Eclipse
  • Views, windows, display panes to move around
  • Console, Javadoc, problems, TODO
  • Errors, warnings, quick fixes, refactoring
  • Java
  • Command line switches and arguments
  • classpath (run programs yourself to check)
  • Directory for examples text my versions

37
Learning Java 3rd, Chap 3
  • Tools of the Trade
  • The Java VM
  • Running Java Applications
  • The Classpath
  • The Java Compiler
  • JAR Files
  • Policy Files
  • Running a program from command line (outside of
    Eclipse, after development)

38
Finished Basics What Next
  • Object-oriented thinking programming
  • Encapsulation
  • Object-oriented design and analysis
  • Rational (now IBM) UML Unified Process
  • Inheritance
  • Dynamic dispatching method overloading,
    polymorphism
  • Chapters 4, 5, 6
  • Chapters 7, 8, 9

39
Temporary Spot, October 1, 2007
  • Last look at Chapter 2 example with threads
  • How to write programs
  • Requirements
  • Iteration (incremental development)
  • Testing (based on requirements and code)
  • Water fall (high level requirements, down hill
    the rest of the way)
  • Top-down (rich underlying Java components)

40
How to Write Programs
  • Waterfall
  • Figure out everything at the beginning
  • Build it with no modification
  • DoD contracting, others with rigid approvals
  • Iterative
  • More like remodeling than building
  • eXtreme Programming (XP) (take everything to the
    extreme)
  • Test Driven Development

41
Federal Life Cycle Perspective
42
Development Cycle
43
Writing a Program
  • Even a big, complicated program should be
    developed in small steps
  • Handling many alternatives in applications
  • First, just do it
  • Second, if tests or configuration file
  • Third, design around a pattern
  • Tests at each stage of development / modification
    (regression tests)
  • Think in terms of change
  • Expand from a central core (iteratively)

44
Object-0riented Programming
  • Encapsulation
  • Objects in Java are instances of classes
  • Issue of what to combine into classes / objects
  • Cohesion, connections, collaboration, complexity
  • Information hiding, decision hiding,
    responsibility
  • Packages
  • Overall structure of application
  • Potential for reuse

45
Class-Responsibility-Collaboration
  • CRC cards are an object-oriented software design
    tool, typically used in determining which classes
    are needed and how they will interact.
  • CRC cards are usually created from index cards on
    which are written
  • The class name
  • Its Super and Sub classes (if applicable)
  • The responsibilities of the class.
  • The names of other classes that the class will
    collaborate with to fulfill its responsibilities.
  • Author
  • Using a small card keeps the complexity of the
    design at a minimum. It focuses the designer on
    the essentials of the class and prevents him from
    getting into its details and inner workings at a
    time when such detail is probably
    counter-productive. It also forces the designer
    to refrain from giving the class too many
    responsibilities. Because the cards are portable,
    they can easily be laid out on a table and
    re-arranged while discussing a design with other
    people.
  • A common method to determine what cards should be
    created is to read a specification for the
    program being designed and consider if each noun
    should be a class and if each verb should be a
    responsibility of the noun or class that it
    belongs to. Naturally, the existence of a noun or
    verb does not require a class or responsibility
    in the program, but it is considered a good
    starting point.

46
Unified Modeling Language
  • UML, UML 2.0 Object Management Group
  • Unified, not universal
  • Rational (Booch) hired (Rumbaugh), bought another
    company (Jacobson), and unified
  • Graphical modeling tool in Eclipse
  • Forward and reverse engineering
  • Class / object diagrams Sequence diagrams Use
    cases

47
Rational Analysis Design Approach
  • (Rational) Unified Process (RUP)
  • Use cases to describe requirements and basic
    functionality
  • Boundary objects to describe interface
  • Refine and implement those boundary objects with
    internal objects that can be further refined
  • Build tests with supporting temporary objects

48
Object-Oriented Inheritance
  • Software reuse
  • Im reusing your classes, but over-riding all
    your methods and hiding all your fields
    (variables).
  • Inheritance is-a
  • Inherited fields
  • Inherited methods
  • Overloaded versus over-ridden methods
  • Building on and refining existing code
  • Composite has-a

49
Food Oriented Inheritance
  • MMs (candy of the millennium MM)
  • Example
  • Three Musketeers Milky Way Snickers
  • Pizza
  • Stone Cold Creamery ice cream, Dairy Queen
    Blizzard, flurry
  • Chinese food
  • Hamburger is more like an interface
  • Pizza Java example in Eclipse next slide

50
Pizza as a Design Example
  • ThinCrustLightSauceRegularCheesePeperoni inherits
    from ThinCrustLightSauceRegularCheese which
    inherits from ThinCrustLightSauce which inherits
    from ThinCrust
  • We might look at pizza as very inheritance
    oriented, but that is not the only way, and maybe
    not the best way to think about it.
  • Inheritance turns out to be cumbersome
  • Composite / aggregation more adaptable
  • Method delegation makes pieces self responsible
  • Factories and abstract factories

51
Beneath Object-Oriented
  • Procedural-style code at lower levels
  • Variables, loops, if-tests, compound statements,
    subprograms, recursion
  • Manipulating state (kept in objects)
  • Functional-style programming
  • When no local state
  • Objects (and thereby methods) as parameters and
    return values
  • Concurrency (multi-threaded)
  • Implicit and later explicit

52
Learning Java 3rd, Chap 4
  • The Java Language
  • Text Encoding
  • Comments
  • Types
  • Statements and Expressions
  • Exceptions
  • Assertion
  • Arrays

53
Program Comments
  • Internal comments
  • For somebody changing the code
  • Assume knowledge of Java (dont explain what)
  • Why you did it
  • Is there something not obvious
  • Relationship to other parts of system
  • External (JavaDoc) comments
  • For somebody using your components
  • User documentation

54
Types
  • Primitive types machine built-in
  • Reference types (user defined types)
  • User created class
  • References passed by value
  • Arrays Strings specially handled
  • Interfaces

55
Statements Expressions
  • Expressions can stand alone as statements
  • Functions and procedures are vary similar
  • Method invocation
  • Variable access
  • Object creation (new), instanceof operator
  • Local declarations and scope
  • Compound statements
  • If/else, Switch, Selection
  • Enumerations

56
Looping / Iteration Patterns
  • Fortran DO loop C/C/Java for loop
  • While/Do (test at top, separate stepping)
  • Do/While (test at bottom, similar)
  • Counting, indexing, ranges
  • Loop variables with local scope in loop
  • Iterator over a structure (enhanced)
  • Nested loops, break, continue, labels
  • Machine language looping instructions used to
    motivate various optimizations

57
Exceptions
  • Try . . . Catch
  • Handling exceptions
  • Exception types
  • Throwing exceptions
  • Finally clause

58
Assertions
  • Have to turn them on to be caught
  • No overhead if turned off
  • Programming by Contract
  • Pre-conditions check with exceptions
  • Post-conditions check with assertions

59
Arrays
  • 0-based subscripting
  • Special treatment within Java type system
  • Anonymous arrays
  • Multidimensional arrays
  • Initializing

60
Learning Java 3rd, Chap 5
  • Objects in Java
  • Classes
  • Methods
  • Object Creation
  • Object Destruction
  • Enumerations

61
Classes, Interfaces, Types
  • Enumerations - enum

62
Method Selection Based on Type
63
How to Write Programs, Again
  • Javadoc for users of your components
  • Internal comments for code changers
  • DRY Dont Repeat Yourself
  • YAGNI You Aint Gonna Need It
  • Dont try to guess ahead of requirements
  • Savings of building now lost if change needed

64
Other Patterns for Code Development
  • Bottom up, inside out, outside in (sort of like
    top-down)
  • Knowing already available components
  • Frameworks for similar applications

65
Divide Your Program into Pieces
  • Pieces that will make the overall system easier
    to understand
  • Pieces that will minimize communication between
    them
  • Pieces that bring together all related info
  • Information hiding, decision hiding
  • Programming language may, or may not, have
    constructs to help in this process
  • Encapsulation, visibility control, interface

66
Program Testing
  • Tests to understand requirements
  • Tests to confirm what program does
  • Assertions about intermediate states
  • Test Driven Development

67
JUnit
  • Testing framework using Java (not some other
    scripting language)
  • Good for idea of having programmers write tests
  • Focus on independence, localization, and
    isolation of tests over perceived speed of
    execution (really pretty efficient with small
    objects the way it is)

68
Learning Java 3rd, Chap 6
  • Relationships Among Classes
  • Subclassing and Inheritance
  • Interfaces
  • Packages and Compilation Units
  • Visibility of Variables and Methods
  • Arrays and the Class Hierarchy
  • Inner Classes

69
Summary of Object-Oriented
  • Encapsulation
  • Object-oriented design and analysis
  • Rational (now IBM) UML Unified Process
  • Inheritance
  • Food examples
  • Composition versus inheritance
  • Dynamic dispatching
  • Overloaded versus over-ridden methods

70
Need Something About GUI
  • Hope to be here Wednesday, October 3
  • Graphical User Interface (GUI)
  • Asynchronous events generated by user activity
    (generally mouse movements, clicks, text input,
    special keys)
  • Event listener interfaces (require implementing
    methods which can be called (back) by events)

71
Event Handling Styles
  • Now that you have seen a few different event
    handlers, it is useful to see some different
    styles.
  • The handlers that you have seen so far have been
    listener objects which happened to contain the
    source object on which the event occurred. But
    this is not mandatory.
  • A class can exist solely for the purpose of
    handling an event. To illustrate, lets create a
    simple class, Detect, which will close a Frame
    when close is selected from the system menu.
  • class Detect extends WindowAdapter public
    void windowClosing(WindowEvent e)
    System.exit(0)
  • The WindowAdapter class is a class which
    implements the WindowListener interface and as
    such provides stubs for each mandated method in
    the interface.
  • L11Button1 is an example using a Detect object as
    a listener.

72
Event Handling Styles L11Button1
  • import java.awt. import java.awt.event. pu
    blic class L11Button1 extends Frame Button
    b1 L11Button1() super("L11 BUTTON
    TEST") setLayout(new FlowLayout())
    b1 new Button("FIRST") add(b1)
    setSize(200,300) setVisible(true)
    addWindowListener(new Detect()) public
    static void main(String args)
    L11Button1 bt new L11Button1()
    class Detect extends WindowAdapter
    public void windowClosing(WindowEvent e)
    System.exit(0)

73
Event Handling Styles
  • The previous method is useful for some events,
    but it fails if a Detect object needs to access a
    member of the L11Button1 class.
  • This can be solved by making the Detect class an
    inner class, as in L12Button2.
  • Then well make it into an anonymous inner class
    in L13Button3.
  • In this last case, the inner class has no name,
    is created on the fly, and although syntactically
    less pleasing is slightly more efficient.

74
Event Handling Styles L12Button2
  • import java.awt. import java.awt.event. pu
    blic class L12Button2 extends Frame Button
    b2 L12Button2() super("L12 BUTTON
    TEST") setLayout(new FlowLayout())
    b2 new Button("SECOND") add(b2)
    setSize(200,300) setVisible(true)
    addWindowListener(new Detect()) class
    Detect extends WindowAdapter public
    void windowClosing(WindowEvent e)
    System.exit(0) public static
    void main(String args) L12Button2 bt
    new L12Button2()

75
Event Handling Styles L12Button2a
  • import java.awt. import java.awt.event. pu
    blic class L12Button2a extends Frame
    Button b2 // moved main up in
    listing public static void main(String
    args) L12Button2a bt new
    L12Button2a() L12Button2a()
    super("L12a BUTTON TEST") setLayout(new
    FlowLayout()) b2 new
    Button("SECOND-a") add(b2) setSize(200,300)
    setVisible(true) // above basically as
    before addWindowListener(new Detect())
    class Detect extends WindowAdapter
    public void windowClosing(WindowEvent e)
    System.exit(0)

76
Event Handling Styles L12Button2b
  • import java.awt. import java.awt.event. pu
    blic class L12Button2b extends Frame
    Button b2 // moved main up in
    listing public static void main(String
    args) L12Button2b bt new
    L12Button2b() L12Button2b()
    super("L12b BUTTON TEST") setLayout(new
    FlowLayout()) b2 new
    Button("SECOND-b") add(b2) setSize(200,300)
    setVisible(true) // above basically as
    before addWindowListener(new Detect())

    // stuff to delete class Detect extends
    WindowAdapter() public void
    windowClosing(WindowEvent e)
    System.exit(0) )

77
Event Handling Styles L12Button2c
  • import java.awt. import java.awt.event. pu
    blic class L12Button2c extends Frame
    Button b2 // moved main up in
    listing public static void main(String
    args) L12Button2c bt new
    L12Button2c() L12Button2c()
    super("L12b BUTTON TEST") setLayout(new
    FlowLayout()) b2 new
    Button("SECOND-b") add(b2) setSize(200,300)
    setVisible(true) // above basically as
    before addWindowListener(new
    WindowAdapter()
    public void windowClosing(WindowEvent e)
    System.exit(0) )

78
Event Handling Styles L13 Button3
  • import java.awt. import java.awt.event. publ
    ic class L13Button3 extends Frame Button
    b3 L13Button3() super("BUTTON
    TEST") setLayout(new FlowLayout()) b3
    new Button("THIRD") add(b3)
    setSize(200,300) setVisible(true)
    addWindowListener(new WindowAdapter()
    public void windowClosing(WindowEvent e)
    System.exit(0)
    ) public static
    void main(String args) L13Button3
    bt new L13Button3()

79
Event Handling Anonymous Inner Classes
  • Event handling is delegated to objects of classes
    implementing listener interfaces
  • The class creating the visible component can
    handle its own events or it can delegate the
    handling to another object.
  • The handling object can be defined by
  • A separately compiled class
  • A separate class in the same file
  • A named inner class, or
  • An anonymous inner class
  • Anonymous inner classes link events and handlers
  • Model View Controller Architecture
  • Model state data, non-visual functionality
  • View visible components (may be multiple per
    model)
  • Controller maps and controls mapping of events
    to model
  • Swing components in with and support
    model-view-controller

80
Swing GUI Development with Eclipse
81
Declarative-like Development
82
Attaching Action Handlers
83
Distributed Java RMI
  • Hope to be here Wednesday, October 10

84
Then Jump to Chapter 9
85
Learning Java 3rd, Chap 9
  • Threads
  • Introducing Threads
  • Threading an Applet
  • Synchronization
  • Scheduling and Priority
  • Thread Groups
  • Thread Performance
  • Concurrency Utilities
  • Conclusion

86
Problems with Concurrency
  • Functional programming versus imperative
  • Program state is part of imperative programming
  • Objects methods and object state
  • Functional programming nested function calls
    returning values without modifying internal state
  • Multiple pure functions can run without
    interference
  • Running threads independently versus having them
    cooperate
  • Running independently and collecting summary

87
Mutable / Non-mutable State
  • Earlier discussion of functional programming
  • Shared memory controlling changes

88
Deeper into Java
  • Reflection
  • Finding out about existing classes
  • Run-time dynamic invocation
  • Generics (new to Java5)
  • Generics in Ada, templates in C
  • Built-in data structure manipulation classes
  • Concurrency, multi-threading
  • Multi-core CPUs even in laptops

89
Learning Java 3rd, Chap 7
  • Working with Objects and Classes
  • The Object Class
  • The Class Class
  • Reflection
  • Annotations

90
Learning Java 3rd, Chap 8
  • Generics
  • Containers Building a Better Mousetrap
  • Enter Generics
  • The Is No Spoon
  • Parameterized Type Relationships
  • Casts
  • Writing Generic Classes
  • Bounds
  • Wildcards
  • Generic Methods
  • Arrays of Parameterized Types
  • Case Study The Enum Class
  • Case Study The sort() Method
  • Conclusion

91
Next Level of Java
92
Monday, October 15, 2007
  • Student Projects incomplete information
  • Thread pools
  • Assertion and JUnit
  • Autoboxing unboxing, enum
  • Garbage collection
  • Inner Classes
  • Reflection
  • UML reverse engineering
  • Patterns

93
Assertions
  • if (!condition) throw new AssertError
    (fatalerror 42)
  • assert (condition) assert a 0 a // to
    show value of a
  • Enable assertions at runtime with -ea
  • Pre-condition checking exceptions
    post-condition checking assertions

94
JUnit
95
Autoboxing and unboxing
  • Primitive types and wrapper objects (e.g., int
    and Integer)
  • Boxing is wrapping primitive value ( new
    Integer(int) )
  • Unboxing is the reverse ( Integer.valueOf() )
  • Was automatic in C, added in Java5

96
Variable-Length Arg. Lists
  • System.out.printf (My name is s and my age is
    s\n, Bob, 103)
  • System.out.printf(Get the s out of s before I
    s\n, item, place, action )
  • void printObjects(Object … list) // list is
    an Object for (Object o list) System.out.pr
    intln(o)

97
enum
  • Better than lists of constants
  • Special kind of class (objects are instances of a
    class, here we name them)
  • List the potential objects
  • Local methods can be individualized

98
Garbage Collection
  • Object finalization in Java is automatic
  • Sometimes object references can be kept without
    realizing it (in maps frequently)
  • Garbage collection
  • Old mark and sweep
  • More modern generational
  • Garbage collection in a separate thread
  • Massive physical (virtual) memories

99
Inner Classes
  • More than just for event handling
  • Top-down iterative development needs to implement
    complicated functionality
  • Text p. 182 ?

100
Thread Pools
101
UML
102
Reverse Engineering
103
Patterns
  • Factory, abstract factory, singleton
  • Façade
  • Observer

104
Singleton
  • public class OnlyOne OnlyOne thing
    null private OnlyOne() // constructor pub
    lic OnlyOne accessor() if (thing null)
    thing new OnlyOne() return
    thing

105
Factory
  • Generating objects of concrete class

106
Abstract Factory
  • Factory generating objects for an interface

107
Singleton
  • Factory returning same object

108
Façade
109
Observer
  • Java way of handling events
  • Event sources and listeners

110
Reflection
  • Self examination (introspection) and examination
    of other objects/classes
  • Text p. 200 ?

111
Monday, October 22, 2007
  • Next Phase of CSE 502
  • What you suggested Wed 10/17
  • Layout managers
  • File I/O and text manipulation
  • Graph plotting (x, y graph)
  • Performance
  • Going for most of the rest of the book
  • More cross discussion of student projects

112
Text, I/O, Web
  • Chap 10 Working with Text
  • Chap 11 Core Utilities
  • Chap 12 Input / Output Facilities
  • Chap 13 Network Programming
  • Chap 14 Programming for the Web
  • Chap 15 Web Applications and Services

113
GUI Swing
  • Chap 16 Swing
  • Chap 17 Using Swing Components
  • Chap 18 More Swing Components
  • Chap 19 Layout Managers
  • Chap 20 Drawing with the 2D API
  • Chap 21 Working w/ Images Other Media

114
Other Topics
  • Chap 21 JavaBeans
  • Chap 23 Applets
  • Chap 24 XML
  • Databases SQL JDBC

115
16 Swing
  • Swing is built on AWT, there are other GUI
    frameworks
  • Lots of books, on-line tutorials, examples
  • AWT peers from underlying OS Swing pure Java
    except at very lowest component
  • AWT look like underlying system Swing control
    look and feel

116
16 Swing
  • Swing Components Figure 16-1 text p. 554

117
Swing Components Performance
  • Demo

118
Components Containers
  • JComponent is swing root
  • Placed in container
  • JComponent is also a kind of container
  • Peers Look-and-Feel
  • Explanation not too useful in programming
  • AWT works with peers in underlying op. sys. to
    look like underlying operating system
  • Swing light-weight, pure Java except at bottom

119
Paint Repaint
  • repaint()
  • Update as soon as possible
  • Sets up request to
  • paint()
  • Implemented, modified by user
  • May be called for lots of reasons
  • Done in event thread

120
MVC Model, View, Controller
  • Historically from Macintosh computer
  • Other models linking GUI with computation
  • Swing is MVC
  • Event listeners observers controllers
  • Event sources observables models
  • Swing is MVC
  • UI-delegate view controller
  • Data model itself
  • More obvious in complicated components

121
Events
  • Events AWT swing
  • Action events
  • Focus events
  • Request focus
  • Manage focus
  • Enabling, disabling, grey-out, ghost
  • Component methods that all inherit
  • Event Summary chart pp. 577-579

122
Mouse Events
  • Mouse
  • Buttons
  • Key modifiers (shift, control, click)
  • Wheel
  • Focus events
  • Adapter classes
  • Dummy adapters (predefined)

123
The AWT Robot
  • Tool for generating what appear like mouse
    movements
  • Should be useful in building test emulators
  • When you see things others have done (special
    tools or environments) thats a hint you could do
    it, too look at open source

124
Multithreading in Swing
  • invokeLater()
  • invokeAndWait()
  • javax.swing.SwingUtilities
  • SwingUtilities.invokeLater( new Runnable()
    public void run() MyCompoent.setVisible(f
    alse) )

125
17 Using Swing Components
  • Buttons and Labels p. 587
  • HTML Text in Buttons and Labels
  • Checkboxes and Radio Buttons p. 590
  • Lists and Combo Boxes p. 593
  • The Spinner
  • Borders

126
Menus
  • Menus
  • Keyboard mnemonics ALT and a letter
  • Keyboard accelerator for when menu not showing
  • Pop-up Menus
  • Component-Managed Pop-ups

127
  • JScrollPane Class
  • JSplitPane Class
  • JTabbedPaneClass
  • Scrollbars and Sliders
  • Dialogs
  • File Selection Dialog
  • Color Chooser

128
18 More Swing Components
  • Text Components
  • TextEntryBox Application
  • Formatted Text
  • Filtering Input
  • Validating Data
  • Password (Say the Magic Word)
  • Sharing a Data Model
  • HTML and RTF for Free
  • Managing Text Yourself

129
  • Focus Navigation
  • Trees
  • Nodes and Models
  • Tables
  • Desktops
  • Pluggable Look-and-Feel
  • Synth, the Skinnable LF

130
Custom Components
  • Generating Events
  • Dial Component
  • Model and View Separation

131
19 Layout Managers
  • Work through authors examples

132
20 Drawing with the 2D API
133
21 Working w/ Images Other Media
  • Loading Images
  • ImageObserver
  • MediaTracker
  • ImageIcon
  • ImageIO
  • Producing Image Data
  • Drawing Animations
  • BufferedImage Anatomy
  • Color Models
  • Creating an Images
  • Updating a BufferedImage
  • Filtering Image Data
  • How ImageProcessor Works
  • Converting an Image to a BufferedImage
  • Using the RescaleOp Class
  • Using the AffineTransformOp Class
  • Saving Image Data
  • Simple Audio NoisyButton.java
  • Java Media Framework - MediaPlayer.java

134
Monday, 2007.10.29
135
10 Working with Text
  • Text-Related APIs
  • Strings
  • Easy to read ? (usually) ? efficient
  • Lots of included methods
  • Comparing strings
  • Searching finding indecies of substrings
  • exampleString.substring(starting, ending) //
    starting index inclusive, ending exclusive

136
More About String Manipulation
  • StringBuilder (Java5) StringBuffer (old,
    synchronized)
  • Multi-line string initialization OK
  • Internationalization (i18n)

137
More Text Manipulation
  • Parsing, Formatting, Tokenizing text
  • Split ? array of strings
  • Scanner java.util.Scanner
  • StringTokenizer - legacy
  • Printf-Style Formatting
  • String.format to format string
  • String conversions
  • Width, precision, justification, flags
  • Formatting with the java.text Package
  • messageFormat replaced by printf()

138
Regular Expressions
  • java.util.regex
  • Describing patterns

139
11 Core Utilities, Math
  • Math Utilities
  • java.lang.Math
  • Usual functions
  • Math.sin(a)
  • java.math
  • BigInteger, Big Decimal
  • Random numbers

140
Dates and Times
  • Working with Calendars
  • Parsing Formatting with DateFormat
  • Printf-style Date Time Formatting
  • Timers

141
Collections
  • Collection Interface
  • Generics
  • Set List Queue Map Arrays linked lists
    trees hash maps
  • Synchronized unsynchronized collections

142
Properties Preferences
  • Properties
  • Specialized hash table for pairs of strings
  • The Preferences API
  • The Logging API
  • Observers and Observables

143
12 Input / Output Facilities
  • October 31, 2007 see you in two weeks
  • Streams
  • Files
  • Serialization
  • Data Compression
  • The NIO Package

144
Input/Output Wrappers
  • Use PrintWriter instead of PrintStream or
    OutputStream
  • Auto-flush

145
13 Network Programming
  • Sockets
  • Datagram Sockets
  • Simple Serialized Object Protocols
  • Remote Method Invocation
  • Scalable I/O with NIO

146
Java Networking and I/O
  • Why Java for Network Applications
  • Basic Web terms, Network layers, IP Addressing
  • URL Uniform Resource Locator
  • Class java.net.URL Constructor Examples
  • Copying files from URL
  • Idea of Sockets, copying with sockets
  • Sockets Java RMI CORBA
  • RMI example interface, client, server
    (implementation)

Networking
147
Why Java for Network Applications
  • Language features (concurrency, exceptions)
  • Built-in objects (information hiding) (more
    straight forward than UNIX and building your own)
  • Protocol handlers, content handlers
  • down load as needed
  • loading classes remotely
  • Heterogeneous networks work together at Java
    level
  • All the other stuff for modern applications GUI,
    databases, security, etc.
  • Performance - individual CPU generally not the
    bottleneck

148
Basic Web Terms
  • TCP/IP - Transport Control Protocol / Internet
    Protocol
  • UDP - User Datagram Protocol
  • URL - Uniform Resource Locator
  • URI - Uniform Resource Identifier (more general,
    research direction)
  • URN - Uniform Resource Name (without location,
    for mirror sites)
  • HTTP - HyperText Transfer Protocol
  • HTML - Hypertext Markup Language
  • SGML - Standard Generalized Markup Language (ISO
    88791986)
  • MIME - Multipurpose Internet Mail Extensions
  • ASCII - American Standard Code for Information
    Interchange

149
Network Layers
  • Very simplified view

Application
Application
Logical Communication
Transport (TCP, UDP)
Transport (TCP, UDP)
IP Layer
IP Layer
Physical layer (bits on the wire) ISO Level 1
Net Head IP Head TCP Head App. Head
Data
150
IP Addressing
  • Four numbers, each 0..255, e.g. 123.123.123.123
    (32 bits)
  • Class C address block
  • first three bytes specified, e.g. 123.123.123.
  • room for 254 addresses (0 and 255 special)
  • Domain names that are easier to remember and use
  • Domain Name Service (DNS) for name resolution
  • Multi-hosting (multiple domain names on one IP
    address) multi-homing (multiple IP addresses on
    one machine
  • localhost 127.0.0.1 local loopback address

151
URL- Uniform Resource Locator
  • protocol//hostnameport/path/filenamesection
  • protocol - file, ftp, http, news, telnet, gopher,
    WAIS
  • hostname - www.pithecanthropus.com or
    123.123.123.123
  • port - 13 (daytime), 20 21 (ftp), 23 (telnet),
    25 (smtp/mail), 37 (time), 43 (whois), 79
    (finger), 80 (http), 110 (pop3/mail), 119
    (nntp/news), 1099 (RMI Registry) defined in
    /etc/services or windows\services
  • path - relative to document root of server, not
    file system root
  • filename - usual default index.html server has
    other options
  • section - named anchor in an HTML document (text
    bookmark)
  • relative and absolute URLs allow moving whole
    collections

152
java.net.URL Constructor Examples
  • public final class URL extends Object implements
    Serializable
  • URL constructor formats match common use public
    URL (--) throws MalformedURLException
  • (String spec)
  • (String protocol, String host, int port, String
    file)
  • (String protocol, String host, String file)
  • (URL context, String spec)
  • try URL u1 new URL(http//www.x.com/a.html)
    catch (MalformedURLException e)
    System.err.println(e)
  • new URL(http, www.x.com, /a.htmlb)
  • new URL(http, www.x.com, 80, /a.html)
  • new URL(u1, other.html)
  • / example / import java.applet.Applet URL u
    new URL(getDocumentBase(), b.html)

153
GetURL Copies Files
  • URL url new URL(args0) InputStream in
    url.openStream() // InputStream in new
    FileInputStream(a.b) OutputStream out new
    FileOutputStream(args1) byte buffer new
    byte4096 int bytes_read while((bytes_read
    in.read(buffer)) ! -1) out.write(buffer, 0,
    bytes_read)
  • Java Examples in a Nutshell, 1st Edition , by
    Flanigan (OReilly)

154
Idea of sockets
  • Computer has (probably) one connection to the net
  • Logical ports subdivide that connection
  • Operating system, network communications driver
    listens and then passes the information to
    waiting programs (sockets)
  • Sockets are independent programs registered to
    receive data
  • Parallel on senders side
  • Sockets can be used for two-way communication
  • Form the foundation for network communication
  • Popularized in Berkeley UNIX as a unifying concept

155
Copy http with sockets
  • Socket soc new Socket(url.getHost(),
    url.getPort()) InputStream from
    soc.getInputStream() PrintWriter to new
    PrintWriter(new OutputStreamWriter(soc.getOutputSt
    ream())) to.println("GET " filename)
    to.flush() byte buffer new byte4096 int
    bytes_read while((bytes_read
    from.read(buffer)) ! -1) to_file.write(buffer,
    0, bytes_read)
  • Examples 9-4 HttpClient

156
Sockets - RMI
  • Distributed systems
  • different address spaces
  • potentially on different hosts
  • ability to communicate
  • Sockets - flexible and sufficient, but require
    applications-level protocols (cumbersome and
    potentially error-prone)
  • Remote Procedure Call (RPC) alternative with
    illusion of calling a local procedure
  • RPC not appropriate for distributed object
    systems where Remote Method Invocation (RMI) is
    better model
  • In RMI a local surrogate (stub) object manages
    the invocation on a surrogate (skeleton) for the
    remote object
  • RMI is an all Java approach to distributed objects

157
Java RMI vs. CORBA
  • Java RMI integrated in the language (JDK 1.1 and
    following)
  • CORBA Common Object Request Broker Architecture
  • OMG - Object Management Group
  • CORBA for a heterogeneous, multi-language
    environment and thus has a language-neutral
    object model
  • IDL - Interface Description Language RMI uses
    Java for its interface descriptions
  • IIOP - Internet Inter-Orb Protocol IIOP
    generally over TCP/IP, also others in JDK 1.2.2
    and later, RMI over IIOP
  • NDI - Naming Directory Interface
  • Evolve together (with CORBA becoming more light
    weight)

158
RMI Common Interface
  • import java.rmi. public interface iCalendar
    extends Remote java.util.Date getDate ()
    throws RemoteException

159
RMI Client
  • public class CalendarUser public static
    void main(String args) iCalendar
    remoteCal try
    remoteCal (iCalendar)
    Naming.lookup("rmi//remote/Calen
    darImpl") t1 remoteCal.getDate()
    .getTime() t2
    remoteCal.getDate().getTime() catch
    (Exception e) e.printStackTrace()
    System.out.println("This
    RMI call took (t2-t1) "
    milliseconds")

160
RMI Server
  • public class CalendarImpl extends
    UnicastRemoteObject
    implements iCalendar public
    CalendarImpl() throws RemoteException
    public Date getDate () throws RemoteException
    return new Date() public
    static void main(String args)
    CalendarImpl cal try
    LocateRegistry.createRegistry(1099)
    cal new CalendarImpl()
    Naming.bind("rmi///CalendarImpl", cal)
    System.out.println("Ready for RMI's")
    catch (Exception e)
    e.printStackTrace()

161
Stubs and Skeletons
  • Java automatically generates stubs and skeletons
    with rmic based on common interface and
    implementation .class file

client
program stub marshall network network unmarshall
stub return program
162
Pulling it together
  • Compile client and server
  • Generating stubs skeletons
  • Remote Method Invocation Compiler (rmic)
  • Start server
  • Run client

163
Callbacks, CORBA, J2EE
  • X11 Windows
  • reversed traditional role of client and server
  • routines on display terminal were called back
    by computer
  • terminal sent information about these routines to
    the server
  • RMI Registry is only one way of objects knowing
    each other
  • CORBA Common Object-oriented Request Broker
    Architecture
  • Microsoft COM, COM, DCOM
  • Java 2 Enterprise Edition (Enterprise Java Beans)

164
About PowerShow.com