Home

My Java and Object-Oriented Analysis and Design Training Material

image

Contents

1. package members declared with no access modifier are acces sible in the class itself and are accessible to and inheritable by code in the same package devdaily com 82 2 8 Classes and objects 2 8 6 Creating Objects e Objects are created using the new construct Body sun new Body Body earth earth new Body e This example declare two references sun earth that can refer to objects of type Body e Using new is the most common way to create objects e Java runtime a allocates enough space to store the fields of the object b initializes the object and c returns a reference to the new object e If the system can t find enough free space it runs the garbage collector e If there is not enough free space available new will throw an Out OfMemoryError exception 2 8 7 Constructors e Constructors have the same name as the class they initialize Body idNum nextID Move the responsibility for idNum inside the Body class Body sun new Body idNum is 0 Body earth new Body idNum is 1 e Constructors can take zero or more parameters Constructors have no return type e Constructors are invoked after the instance variables of the new object have been assigned their default initial values and after their explicit initializers are executed devdaily com 83 2 8 Classes and objects Constructor example e The following three classes demonstrate how
2. Business people and developers must work together daily throughout the project Build projects around motivated individuals Give them the environ ment and support they need and trust them to get the job done The most efficient and effective method of conveying information to and within a development team is face to face conversation devdaily com 53 1 9 The Agile Alliance e Working software is the primary measure of progress e Agile processes promote sustainable development The sponsors de velopers and users should be able to maintain a constant pace indefi nitely e Continuous attention to technical excellence and good design enhances agility e Simplicity the art of maximizing the amount of work not done is es sential e The best architectures requirements and designs emerge from self organizing teams e At regular intervals the team reflects on how to become more effective then tunes and adjusts its behavior accordingly devdaily com 54 1 10 Introduction to Extreme Programming 1 10 Introduction to Extreme Programming This is a simple introduction to Extreme Programming taken largely from the text eXtreme Programming explained the white book 1 10 1 Risk The Basic Problem Quoting from the white book the basic problem of software development is risk Here are some examples e Schedule slips e Project canceled e System goes sour e Defect rate e Bus
3. e CloneNotSupportedException Four different attitudes a class can have towards clone e Support clone e Conditionally support clone e Allow subclasses to support clone but don t publicly support it e Forbid clone devdaily com 100 2 10 Extending Classes 2 10 13 Extending classes how and when e Ability to extend classes large part of the benefits of OOP e Creates an IsA relationship not a HasA relationship e Employee Role example see text 2 10 14 Designing a class to be extended e Choose the access for each part of a class design carefully public protected private e If your design will have subclasses design your protected parts care fully Bad effects of public fields e Fields can be modified at any time by a programmer e No way to add functionality Non final classes have two interfaces e Public interface for programmers using the class e Protected interface for programmers extending the class devdaily com 101 2 11 Interfaces 2 11 Interfaces 2 11 1 Introduction Interfaces are a way to declare a type consisting only of abstract methods and related constants classes and interfaces An interface in Java is an expression of pure design whereas a class is a mix of design and implemen tation 2 11 2 Objectives Upon completion of this section students will Describe an interface Define the differences between single and multiple inh
4. Questions to help identify actors Who is interested in a certain requirement Who installs the system Who starts and stops the system Where in the organization is the system used Who will benefit from use of the system Who will supply the system with this information use this informa tion and remove this information Who will support and maintain the system Does the system use an external resource Does one person play several different roles Do several people play the same role Does the system interact with a legacy system What other systems use this system Who gets information from this system devdaily com 35 1 7 A sample process Use Cases Use Case a sequence of actions that an actor performs within a system to achieve a particular goal The purpose of this stage is to capture user requirements of the new system using use case diagrams e Definition A sequence of actions that an actor performs within a system to achieve a particular goal e A use case describes one or more courses through a user operation The basic course must always be present alternate courses are optional e Basic course the main start to finish path the user will follow under normal circumstances e Alternate course infrequently used path an exception or an error condition e Stated from the perspective of the user as a present tense verb phrase in an active voice AdmitPatient Do Trade Entry Generate Repo
5. and that follow the method s signature public void speak System out println Hey Barney Invoking a Method e Provide an object reference and the method name separated by a dot fred speak e Parameters are passed to methods as a comma separated list e A method can return a single value as a result such as an int devdaily com 91 2 9 Methods and parameters public int add int a int b return atb e A method can return no result public void setFirstName String firstName this firstName firstName The this Reference e Occasionally the receiving object needs to know its own reference public void move double x double y this x X this y y devdaily com 92 2 10 Extending Classes 2 10 Extending Classes 2 10 1 Introduction e It is easy for one Java class to extend the behavior of another Java class e This capability is usually referred to as polymorphism which means that an object of a given class can have multiple forms 2 10 2 Objectives e Upon completion of this section students will be able to e Extend existing classes e Define the terms subclass superclass overloading and overriding Define how constructors of subclasses operate e Define the implications of marking a class or method as final Discuss the considerations of cloning classes devdaily com 93 2 10 Extending Classes 2 10 3 An extend
6. and thread support Object s utility methods e equals Object o e hashCode e clone devdaily com 98 2 10 Extending Classes getClass finalize 2 10 10 Anonymous classes Use these when the weight of a full class seems too much for your needs Extend a class or implement an interface Defined at the same time they are created with new Defined in the new expression Cannot have their own constructors Can easily become hard to read Avoid anonymous classes longer than six lines Use them only in the simplest of expressions 2 10 11 Abstract Classes and methods Helpful when some of the behavior is defined for most objects of a given type but some behavior makes sense for only particular classes and not the superclass Declare classes that define only part of an implementation Each method not implemented in an abstract class is marked abstract A class with any abstract methods must be declared abstract Abstract methods must be implemented by subclasses that are not abstract themselves 2 10 12 Cloning objects A clone method returns a new object whose initial state is a copy of the current state of the object on which clone was invoked Subsequent changes to the clone will not affect the state of the original Object clone devdaily com 99 2 10 Extending Classes Three major considerations in writing a clone method e Empty Cloneable interface e Object clone method
7. e Simplicity the art of maximizing the amount of work not done is es sential e The best architectures requirements and designs emerge from self organizing teams e At regular intervals the team reflects on how to become more effective then tunes and adjusts its behavior accordingly Design Patterns e Repeating patterns Her garden is like mine except that in mine I use astilbe e Recurring solutions to design problems you see over and over e A set of rules describing how to accomplish certain tasks in the realm of software development e Made famous by the text Design Patterns by Gamma Helm et al devdaily com 60 Chapter 2 Day 2 The Java Programming Language 2 1 Introduction 2 1 1 Chapter objectives Review the Java design goals Understand the reserved Java keywords Work with Java strings and arrays Create standalone Java applications Create Java classes that use and extend one another Write programs that use and handle exceptions Learn about Java interfaces Understand how to package your Java classes 61 2 1 Introduction 2 1 2 Java design goals Simple syntax like C but easier Secure compile and runtime support for security Distributed built to run over networks Object oriented designed from the ground up to be object oriented Robust strongly typed memory management exception handling Portable Write Once Run Anyw
8. inside of loops where many INSERT s or UPDATE s need to be done at one time devdaily com 141 4 1 Databases and JDBC 4 1 7 A real method The following method was copied from a production software application Note that it uses a PreparedStatement for the syntactical ease of use that the PreparedStatement offers public String getPurchaserEmailAddress int orderld throws SQLException Connection connection null try String email null connection ConnectionPool getConnection String query SELECT email FROM orders WHERE order_id PreparedStatement emailQuery connection prepareStatement query emailQuery setInt 1 orderld ResultSet rs emailQuery executeQuery if rs next email rs getString 1 return email finally ConnectionPool freeConnection connection devdaily com 142 4 2 JUnit 4 2 JUnit 4 2 1 Is Testing Important Do you think testing your software code is important Consider the following examples 4 2 2 Mars Orbiter A failure to recognize and correct an error in a transfer of information be tween the Mars Climate Orbiter spacecraft team in Colorado and the mis sion navigation team in California led to the loss of the spacecraft last week preliminary findings by NASA s Jet Propulsion Laboratory internal peer review indicate The peer review preliminary findings indicate that one team used English units e
9. lt sandwich price 2 00 gt lt meat gt Pastrami lt meat gt lt bread gt Rye lt bread gt lt cheese slices 1 gt Swiss lt cheese gt lt condiments gt lt condiment gt mustard lt condiment gt lt condiment gt pepper lt condiment gt lt condiments gt lt sandwich gt e In the example above lt sandwich gt lt condiment gt and all tags within lt gt are elements e Elements can be nested within each other infinitely deep e price and slices are attributes of their respective elements e XML must be well formed to be porcessed All tags are closed lt bread gt Rye lt bread gt or lt bread gt which denotes an empty element devdaily com 134 3 14 Survey of other server side Java technologies Elements must be closed on the same level they start lt sandwich gt lt meat gt lt sandwich gt lt meat gt is not well formed All attributes are within single or double quotes The structure of a particular XML document can be described with Document Type Definitions DTD or schemas Instances of that document can then be validated against the corresponding DTD or schema Why use XML Flexible hierarchical data formatting language that can easily be read by humans as well as programs Readily available tools for document creation parsing and vali dation Plaform and programming language neutral The Java API for XML Processing JAXP defines a standard int
10. 2 ODOC VES Ni ee has Shek Te ee oy Be i s 102 2 11 8 An example interface 102 2 11 4 Single inheritance versus multiple inheritance 103 2 11 5 Extending Interfaces 103 2 11 6 Implementing Interfaces 103 2 11 7 Using an Implementation 104 2 11 8 Marker Interfaces 0 104 2 11 9 When to Use Interfaces 104 2 12 EXCEptions ario ee ee ee es Be ye 105 2 12 1 Introduction 2 0000 105 2 12 2 ODjeCtives ies a ee AS PS ee ee eS 105 2 12 3 Creating exception types 105 212A APO a A a A ne 106 2 12 5 The throws clause o 106 2 12 6 try catch and finally 106 2 12 7 When to use exceptions 107 218 Packages o sc ns o rs io 108 JAS Titroductlio oi a aed 5 108 2 13 2 Package Naming 108 2 13 3 Package Access o o 108 2 13 4 Package Contents 200 4 108 251315 7 H Xam ples 3 2 ace a ke ooh Se GOR ae BP GAR ee ee ed 109 3 Day 3 Standard Libraries amp Server side Programming 110 Del OD IECtIVES ee Sc eek a eh a En ele Ee ook a 110 3 2 IO Streams and readers 2 22 0004 111 3 3 Java networking a 113 3 3 1 Introduction 20 113 Die DOCKET a det Lig AAA an ie Ae ee 113 33 3 ServerSocket 2 4 23 hw a Sade BS 113 3 3 4 ServerSocket li
11. 6 Run the test and see it pass 7 Refactor for clarity and once and only once 8 Repeat from the top One of the great things to come out of the recent Extreme Programming movement has been to bring unit testing to the forefront of every developers thought process devdaily com 147 4 3 Best practices 4 3 Best practices e Very short iterations and immediate feedback XP RUP Working backwards and ruthless testing Junit e Use source code control CVS Use build tools Ant e Communicate communicate communicate XP e Don t live with broken windows e Code generators e On site customer XP e Don t repeat yourself DRY Business ROI devdaily com 148 4 4 Refactoring 4 4 Refactoring Refactoring is a technique to restructure code in a disciplined way Code that smells e Refactoring is a technique to restructure code in a disciplined way e A change to the system that leaves its behavior unchanged but en hances some nonfunctional quality simplicity flexibility understand ability performance Like Design Patterns there is a long list of well known refactorings e Add Parameter e Change Reference to Value e Change Value to Reference e Decompose Conditional e Duplicate Observed Data e Encapsulate Collection e Encapsulate Downcast e Extract Class e Extract Interface e Extract Method e Extract Subclass e Extract Superclass e Hide Delegate e Hide
12. Collections framework String item String it next System out println item 3 8 1 Lists e In addition to the standard collection methods the List interface al lows for random access of elements through its get and set methods e List indices are zero based so list get list size is not a valid element List stuff new ArrayList stuff add Apple stuff add Orange what s the last item Indexes are zero based System out println stuff get stuff size 1 change the first item to a pear stuff set 0 Pear now iterate Iterator it stuff iterator while it hasNext String item String it next System out println item e ListIterator allows element addition removal and replacement during iteration e The java util package provides two new List implementations Ar rayList and LinkedList e Vector is a legacy class retrofitted to the new Collection framework and is thread safe devdaily com 121 3 8 Collections framework 3 8 2 Maps e Maps associate the data elements in the collection with keys The keys are derived from type Object and may be different a type than the data The get and put methods provide access to elements at a particular key Map userAges new HashMap ages put John new Integer 25 ages put Nicole new Integer 32 ages put Bob new Integer 43 How old is Bob Integer bobsAge Integer userA
13. Insufficient testing Subjective project status assessment Failure to attack risk e Uncontrolled change propagation e Insufficient automation 1 2 4 Software development best practices Finally the same text identifies these best practices e Develop software iteratively e Manage requirements e Use component based architectures Visually model software Verify software quality Control changes to software Undetected inconsistencies in requirements designs and implementa devdaily com 10 1 3 Introduction to OO concepts 1 3 Introduction to OO concepts What does it mean to be object oriented The big three concepts are encapsulation polymorphism and inheritance but the text Fundamentals of Object Oriented Design in UML 12 specifies that the following criteria are necessary for a language to be considered object oriented I 10 11 Encapsulation the grouping of related ideas into unit Encapsulating attributes and behaviors Inheritance a class can inherit its behavior from a superclass parent class that it extends Polymorphism literally means many forms Information implementation hiding the use of encapsulation to keep implementation details from being externally visible State retention the set of values an object holds Oject identity an object can be identified and treated as a distinct entity Message p
14. Overriding methods e You override the signature of a method from a superclass e Overriding methods must have argument lists with the identical type and order as the superclass e When you override a method of a superclass you should honor the intended behavior of the method devdaily com 86 2 8 Classes and objects 2 8 12 Static members e A static member is a member that exists only once per class as op posed to once per object e When you declare a field to be static that means that this field exists only once per class as opposed to once for each object such as the nextID field of the Body object e A static method is invoked on behalf of the entire class e A static method can access only static variables and static methods of the class prime Primes nextPrime id Vehicle currentID 2 8 13 Initialization Blocks e A class can have initialization blocks to set up fields or other necessary states e Typically these blocks are static e Most useful when simple initialization clauses on a field declaration need a little help class Primes protected static int knownPrimes new int 4 static knownPrimes 0 2 for int i 1 i lt knownPrimes length i knownPrimes i nextPrime e You can also have non static initialization blocks devdaily com 87 2 8 Classes and objects 2 8 14 Garbage collection and finalize Java performs garbage collection for you and eli
15. Supplementary requirements are documented e A software architecture description is created e An executable architectural prototype is created devdaily com 27 1 6 The Rational Unified Process RUP e A revised risk list and business case are created e A development plan for the overall project is created e An updated development case is created specifying the process to be used Other artifacts e Construction plan e Software prototypes e Risk identification and management plan A test plan A data dictionary e A preliminary user manual devdaily com 28 1 6 The Rational Unified Process RUP 1 6 3 Construction phase The The Rational Unified Process An Introduction 9 specifies the fol lowing objectives activities and deliverables from a construction phase Objectives e Minimize development costs by optimizing resources and avoiding un necessary scrap and rework e Achieving adequate quality as rapidly as practical e Achieving useful versions as rapidly as practical Activities e Resource management resource control process optimization e Complete component development and testing e Assessment of product releases against acceptance criteria Deliverables e The software product integrated on the adequate platforms e User manuals e A description of the current release devdaily com 29 1 6 The Rational Unified Process RUP 1 6 4 Transition The tex
16. b gt Bread lt b gt lt xsl value of select bread gt lt br gt lt b gt Cheese lt b gt lt xsl value of select cheese slices gt slice s of lt xsl value of select cheese gt lt br gt lt br gt lt b gt Cost lt xsl value of select price gt lt b gt lt body gt lt html gt lt xsl template gt lt xsl stylesheet gt Output lt html gt lt head gt lt title gt My Sandwich lt title gt lt head gt lt body gt lt b gt Meat lt b gt Pastrami lt br gt lt b gt Bread lt b gt Rye lt br gt lt b gt Cheese lt b gt 1 slice s of Swiss lt br gt lt br gt lt b gt Cost 2 00 lt b gt lt body gt lt html gt devdaily com 136 3 14 Survey of other server side Java technologies The JAXP defines the API for executing XSLT transformations 3 14 3 Enterprise Java Beans Allows the developer to write components without explicitly coding for database storage transactions thread safety or remote invocation XML configuration files are used to mark how components are mapped to databases which methods require transactions and how the com ponents can be accessed The EJB specification is implemented by many vendors including IBM Borland BEA Oracle and Macromedia There are also a few open source implementations 3 14 4 Java Messaging Service Provides asynchronous message based communication to Java appli cations There are two styles of JMS Queue
17. constructors are called for classes and superclasses public class ParentClass public ParentClass System out println ParentClass constructor was called public class ChildClass extends ParentClass public ChildClass System out println ChildClass constructor was called public class Main public static void main String args ChildClass cc new ChildClass 2 8 8 Methods e Here is a sample method for the Body class The method name is toString public String toString String desc idNum name if orbits null desc orbits orbits toString return desc e Returns type String devdaily com 84 2 8 Classes and objects Methods contain the code that understands and manipulates an ob ject s state e Methods are invoked as operations on an object using the dot operator e Each method takes a specific number of parameters e Each parameter has a specified type primitive or object e Methods also have a return type or void Parameter values e All parameter methods are pass by value e Values of a parameter are copies of the values in the invoking method e When the parameter is an object the object reference is passed by value e End result primitives cannot be modified in methods objects can Using methods to control access e If data fields attributes are public programmers can change them e Gene
18. lets you define some or all of the implementation e Any major class you expect to be extended should be an implementa tion of an interface devdaily com 104 2 12 Exceptions 2 12 Exceptions 2 12 1 Introduction e Applications can run into many kinds of errors during execution e Java exceptions provide a clean way to check for errors without clut tering code and provide a mechanism to signal errors directly e Exceptions are also part of a method s contract e An exception is thrown when an unexpected error condition is encoun tered e The exception is then caught be an encompassing clause further up the method invocation stack 2 12 2 Objectives Upon completion of this section students will be able to e Create their own Exception class e Throw an exception e Define the three choices you have when a method throws an exception Use try catch finally to run a method that may throw an exception e Describe the purpose of the finally clause and when it is run e Make better decisions about when to throw exceptions in your code 2 12 3 Creating exception types e Exceptions are objects e Must extend the class Throwable or one of it s subclasses e By convention new exception types extend Exception a subclass of Throwable public class BadPizzaException extends Exception public String attrName devdaily com 105 2 12 Exceptions BadPizzaException String name super BadPizzaExcepti
19. method ias Tee ee ee E a 142 42 JUnit 2 fea hea a i ee kA ek aS Get 143 4 2 1 Is Testing Important 143 42 2 Mars Orbiter ey ii cs ed 143 4 223 USS Yorktown va AB eA Me ho bae Ed 143 4 2 4 Types Of tests 143 4 2 5 Unit Testing 101 144 4 2 6 Goals of unit testing 144 4 2 7 Unit Testing with JUnit 145 4 2 8 A sample JUnit session 145 42 9 Recaps ato a d e eee aa aa 147 4 3 Best practic s s so armoton e o 8 Aa oe eee as 148 4A Refactoring la LA o ana a Gea A 149 din Final Project 2 220 a A Sve TAD 150 devdaily com Chapter 1 Day 1 Object Oriented Software Development 1 1 Credits and Other Material This training material about the Java Programming Language and Object Oriented Programming methods is always used with at least two other books to whom we owe a great deal of credit These books are 1 The Java Programming Language by Arnold and Gosling 2 Use Case Driven Object Modeling With Uml A Practical Approach by Rosenberg and Scott Many other books and reference materials have been used in the creation of this material and they are all listed in the bibliography at the end of this material 1 2 Why 00 1 2 Why 00 1 2 1 Benefits of object oriented programming Why has object oriented programming gone from being something to think about to being a de facto standa
20. method throws exception UnknownName The name is unknown Cexception IllegalArgumentException The name is lt code gt null lt code gt deprecated e Marks an identifier as being unfit for continued use e Code using a deprecated type constructor method or field will gen erate a warning when compiled begin enumerate item item deprecated Do not use this anymore item end enumerate author e Specify the author of the code author Alvin Alexander version e Specify an arbitrary version version 1 11 devdaily com 73 2 6 Comments and Javadoc since e Specify an arbitrary version specification that denotes when the tagged entity was added to your system since 2 1 2 6 3 A comment example e A heavily commented Attr class class Attr begin enumerate item The attribute name end enumerate end enumerate private String name begin enumerate item The attribute value end enumerate end enumerate private Object value null Creates a new attribute see Attr2 public Attr String name this name name 2 6 4 Notes on Usage e Use the javadoc command to print a separate set of HTML javadoc pages for your classes devdaily com 74 2 6 Comments and Javadoc e See http java sun com j2se 1 4 docs api for an example of javadoc documentation pages for the Java2 Platform e Comment skew comments become out of date
21. the Unix tar command 2 2 2 A first application e Assuming you have the JDK downloaded installed create a first Java application public class Hello public static void main String args System out println Hello world e Save the file as Hello java e Compile the file to Java bytecode javac Hello java e Run the program java Hello devdaily com 64 2 2 First Steps with Java 2 2 3 main When you run a Java application the system locates and runs the main method for that class The main method must be public static and void The main method must accept a single argument of type String The arguments in the String array passed to main are program argu ments or command line arguments An application can have any number of main methods because each class can have one This is good because each class can have a main method that tests it s own code devdaily com 65 2 3 Variables constants and keywords 2 3 Variables constants and keywords 2 3 1 Primitive data types e Java has built in primitive data types e These primitives support integer floating point boolean and charac ter values e The primitive data types of Java are boolean either true or false char 16 bit Unicode 1 1 character byte 8 bit integer signed short 16 bit integer signed int 32 bit integer signed long 64 bit integer signed float 32 bit floating point d
22. while class float native switch const for new synchronized continue goto package this Fibonnaci program e Here is a Fibonnaci program from The Java Programming Language class Fibonacci 4 public static void main String args int lo 1 int hi 1 System out println lo while hi lt 50 System out printin hi hi lo hi lo hi lo e Type this code into the proper filename e Compile and run the program e Discuss the results devdaily com 68 2 4 Arrays 2 4 Arrays An array is a collection of variables of the same type A variable declared in brackets is an array reference Three steps Declaration tell the compiler what the name is and the type of its elements Construction Initialization int numbersl declaration numbers new int 100 construction for int i 0 i lt 100 i numbers i i String username float balance e Components of an array are accessed by a simple integer index Element indexing begins with the number 0 username 0 Fred username 1 Barney e The size of an array is easily accessed with the length attribute for int i 0 i lt username length i System out println The user s name is username i Indexing past the end of an array throws an exception e Multidimensional arrays can be created devdaily com 69 2 5 Strings 2 5 String
23. 2 38 HelloWorldServlet 0 128 3 12 4 Servlet lifecycle o o o 129 3 12 b HTTP Servlet o As ic a a a 129 3 12 6 HTTPServletRequest 129 3 12 7 HTTPServletResponse 129 JavaServer Pages 2 ee ee 130 3 13 1 What isa JSP 4 baea ed n ioa ee Bl a 130 3 13 2 JSP engine container A Pac Be be HO 130 3 13 3 Translation time and request time 130 3 13 4 Scriptlets lt 131 3 13 5 Expressions a ss o e eraio a Ea e 131 3 13 6 Declarations o e e 131 3 13 7 Directives 131 3 13 8 Implicit Objects o 132 devdaily com 5 Contents 3 13 9 Exception handling 133 3 14 Survey of other server side Java technologies 134 3141 KM Grea ra ae eka Re Re ae eee es 134 STAD XS TP fe oa o eat othe eget An ek white ee ae Y 135 3 14 3 Enterprise Java Beans 02 137 3 14 4 Java Messaging Service 137 4 Day 4 Databases Best Practices and Final Project 138 4 1 Databases and JDBC 2 138 4 1 1 Getting things set up 138 4 1 2 Connecting to the database 138 AAS Statements ca a ae 139 4 1 4 getXxXX methods o 140 4 1 5 Updating the database 140 4 16 PreparedStatements 141 ANT A Teal
24. 48 a Ga a ek 83 28 8 Methods a eg pa Ate a pad ed at 84 22820 tis eek oo ao A oe Bo eee ye E N 85 2 8 10 Overloading methods 86 2 8 11 Overriding methods 86 2 8 12 Static members 2 0000005 87 2 8 13 Initialization Blocks 87 2 8 14 Garbage collection and finalize 88 2 8 15 The toString Method 89 2 8 16 Native Methods o aoaaa 89 2 9 Methods and parameters o o ao a a a 000002 ee 91 DIA Methods naar a aaa a ei ara ee Ke den eee BY 91 2 10 Extending Classes a 93 2 10 1 TritrOduetiOnii vx p ia e a 93 2 10 2 Objectives i mia a a ee a Be a 93 2 10 3 An extended class o oo 0084 94 2 10 4 A simple example o 95 2 10 5 What protected really means 96 2 10 6 Constructors in extended classes 96 2 10 7 Overriding methods hiding fields and nested classes 97 2 10 8 Marking methods and classes final 98 devdaily com 3 Contents 2 10 9 The object class o o 98 2 10 10 Anonymous classes o 99 2 10 11 Abstract Classes and methods 99 2 10 12 Cloning Objects o 99 2 10 13 Extending classes how and when 101 2 10 14 Designing a class to be extended 101 2 11 Interfaces seis eth a a ne e 102 211 1 Introductions sansir oe eae A E fa 102 211
25. 8 Collective Ownership 9 Continuous Integration 10 40 Hour Week 11 On Site Customer 12 Coding Standards devdaily com 57 1 11 OO Summary 1 11 OO Summary This section provides a summary of our Day One activities 1 11 1 OO Concepts Software concepts essential to object orientation e Encapsulation the grouping of related ideas into unit Encapsulating attributes and behaviors e Inheritance a class can inherit its behavior from a superclass parent class that it extends e Polymorphism literally means many forms e Information implementation hiding the use of encapsulation to keep implementation details from being externally visible e State retention the set of values an object holds e Oject identity an object can be identified and treated as a distinct entity e Message passing the ability to send messages from one object to another e Classes the templates blueprints from which objects are created e Genericity the construction of a class so that one or more of the classes it uses internally is supplied only at run time 1 11 2 UML The UML defines nine standard diagrams 1 Use Case 2 Class 3 Interaction a Sequence b Collaboration devdaily com 58 1 11 OO Summary T Package State Activity Deployment Rational Unified Process e Inception a discover phase where an initial problem statement and functiona
26. Introduction to Java and OOA 00D for Web Applications Alvin J Alexander devdaily com Copyright 2009 Alvin Alexander devdaily com All Rights Reserved Contents 1 Day 1 Object Oriented Software Development 7 1 1 Credits and Other Material 7 12 WHY A hk Wh a Po ee eG 8 1 2 1 Benefits of object oriented programming 8 1 2 2 Symptoms of software development problems 9 1 2 3 Root causes of project failure 9 1 2 4 Software development best practices 10 1 3 Introduction to OO concepts o 11 13 1 Encapsulation s sacada ara 11 1 3 2 Inheritance 2 2 4 gt 2 yaa a a BE 12 133 Polymorphism 000 12 1 3 4 Abstraction with objects 0 13 1 3 5 Message passing 2 000002 2 ee 13 1 4 UML summary 0200004 14 1 4 1 Standard diagrams 14 1 5 Object Oriented Software Development 22 1 5 1 Why have a process o a 22 1 6 The Rational Unified Process RUP 24 1 6 1 Inception phase o o 25 6 2 Elaboration o aros te Ge ta Dd 27 1 6 3 Construction phase o 29 16 4 lt Transition il A A E 2 30 1 7 A sample process oni misr riian pa 0 0000 be eee eee 31 1 7 1 Domain modeling 0 4 31 1 7 2 Use case modeling 2 000 35 1 7 3 Robustness analysis 2 000 40 1 7 4 Interact
27. Method e Inline Class e Inline Method e Inline Temp e Many more e http www refactoring com devdaily com 149 4 5 Final project 4 5 Final project Note the final project will vary per class devdaily com 150 Bibliography 10 11 12 13 14 15 16 17 Cockburn Surviving Object Oriented Projects Hunt Thomas The Pragmatic Programmer http java sun com docs books tutorial Sun s online tutorials Rosenberg Scott Use Case Driven Object Modeling with UML A Practical Approach Fowler UML Distilled Schneider Winters Applying Use Cases Cockburn Writing Effective Use Cases http books txt com use case templates Kruchten The Rational Unified Process Alhir UML in a Nutshell Visual Modeling with UML Page Jones Fundamentals of Object Oriented Design in UML Arnold Gosling Holmes The Java Programming Language Third Edition Hall Core Servlets and JavaServer Pages Sun JDBC API Tutorial and Reference Second Edition Fowler Refactoring Improving the Design of Existing Code Kernighan Pike The Practice of Programming 151 Bibliography 18 19 20 21 22 23 24 http java sun com http www xprogramming com http www extremeprogramming org http www junit org http www martinfowler com http members aol com acockburn Alistair Cockburn http www sei cmu edu cmm cmm html Capability Maturity Model for Sof
28. Method Invocation RMI works and when where it is used Learn how to use the classes in the Collections API Gain an overview of creating international applications Learn the basics behind the HTTP protocol Learn how to use JavaServer Pages JSPs and Java Servlets 110 3 2 IO Streams and readers 3 2 IO Streams and readers e The java io package provides a rich framework and class library for reading and writing any type of data text numbers images in streams from any type of location disk network memory The package provides 2 class hierarchies one for byte streams the other for character streams e Base classes for reading data InputStream for byte streams Reader for character streams Base classes for writing data OutputStream for byte streams Writer for character streams Example of copying one file to another Reader in new FileReader one txt Writer out new FileWriter two txt int token 1 while token in read 1 out write token out close e The library uses the decorator pattern to add flexible stream han dling By chaining constructors of various classes you can change how streams are read or written Examples 1 We need to read some data on disk and for performance reasons the read operation should be buffered Reader bufferedFileIn new BufferedReader new FileReader datafile 2 Read an in memory byte array as UTF 8 encoded characte
29. agram e Describes the types of objects in the system and the static relation ships between them e Two main kinds of static relationships Associations Has A Subtypes Is A devdaily com 15 1 4 UML summary JDialog AAA CloneProcessDialog ProcessGroupEditDialog ProjectEditDialog ProcessDETEditDialog EntityEditDialog com devdaily Fptracker view EntityEditDialog ProcessEditDialog Figure 1 2 A high level class diagram showing the relationships between classes devdaily com 16 1 4 UML summary ProcessController ay currentConnection Connection ay currentProcessiD int ay currentProjectiD int ay processDETTableModel ProcessDETTableModel By processEditDialog ProcessEditDialog addRowToTableModel void cloneProcess void createProcessTableModel ProcessTableModel deleteRowFromTablemodel void displayDETEditor void displayFTREditor void getListOfProcessDETx List getListofProcesses List saveProcessDET3 void saveProcessesDuringClone void startCloneProcessProcess void updateProcessByProcessiD void getListOfEntitiesNotRelatedToTheProcesx List ge getNumberOfProcessDETsThatHaveSNamet int gf saveProcessDETsPerProcess void ge saveProcessFTRsPerProcesz void setProjectAndProcessiDs void Figure 1 3 A class diagram showing the detailed attributes and behavior
30. amic System Development Method Larger heavier processes are typically built around the Unified Modeling Language or UML 1 5 1 Why have a process Create a product that users want Make the process manageable and predictable Capability Maturity Model CMM from the Carnegie Mellon Univer sity Software Engineering Institute defines five levels of maturity Traditional development process Waterfall Analysis Design Code Test Spiral process Risk Analysis Systems Analysis User Feedback De sign Code Test User Feedback Objectory defines the four project phases of Inception Elaboration Construction Transition Completion of each Objectory phase marks a major milestione Objectory uses iteration to make complex projects possible devdaily com 22 1 5 Object Oriented Software Development Level 5 Maturity Optimizing Level 4 Managed Level 3 Defined Level 2 Repeatable Level 1 Ad hoc Figure 1 8 Steps of the Capability Maturity Model e The process defines ways to make iterative projects manageable e Model the system before developing it in the same way an architect models a new facility before building it devdaily com 23 1 6 The Rational Unified Process RUP 1 6 The Rational Unified Process RUP The Rational Unified Process formally consists of the following steps e Inception a discover phase where an initial problem statement and functional requirem
31. as the source code changes over time e Some programmers write documentation others do not e Some businesses have technical writers that end up needing write ac cess to your Java source code files devdaily com 75 2 7 Flow control and loops 2 7 Flow control and loops 2 7 1 Introduction A program consisting of only consecutive statements is immediately use ful but very limited The ability to control the order in which statements are executed adds enormous value to any program This lesson covers all the control flow statements that direct the order of execution except for exceptions 2 7 2 Objectives Upon completion of this section students will be able to e Define expression statements and declaration statements e Describe the operation of Java s control flow statements e Use Java s if else switch while do while and for statements e Use labels and labeled break and continue statements 2 7 3 Statements and blocks e Two basic statements expression statements declaration statements e Expression statements such as i have a semi colon at the end Expressions that can be made into statements e Assignment those that contain e Prefix or postfix forms of and e Methods calls e Object creation statements new operator Declaration statements e Declare a variable and initialize it to a value e Can appear anywhere inside a block devdaily com 76 2 7 Flow contro
32. assing the ability to send messages from one object to another Classes the templates blueprints from which objects are created Genericity the construction of a class so that one or more of the classes it uses internally is supplied only at run time Test here More testing here 1 3 1 Encapsulation The grouping of related items into one unit e One of the basic concepts of OO e Attributes and behaviors are encapsulated to create objects e OO modeling is close to how we perceive the world devdaily com 11 1 3 Introduction to OO concepts Implementation details are hidden from the outside world We all know how to use a phone few of us care how it works The packaging of operations and attributes representing state into an object type so that state is accessible or modifiable only through the objects interface Encapsulation lets builders of objects reuse already existing objects and if those objects have already been well tested much larger and more complex systems can be created 1 3 2 Inheritance A subclass is derived from a superclass An Employee is a Person The subclass inherits the attributes and behavior of the superclass The subclass can override the behavior of the superclass Notice the use of the Is A phrase to describe inheritance Inheritance promotes re use 1 3 3 Polymorphism Literally means many forms A method can have many different forms of beha
33. be e Recurring solutions to design problems you see over and over e A set of rules describing how to accomplish certain tasks in the realm of software development e A list of some of the most well known design patterns Factory Abstract Factory Singleton Builder Prototype Adapter Bridge Composite Decorator Facade Flyweight Proxy Chain of Responsibility Command Interpreter Iterator Mediator Memento Observer State Strategy Template Visitor Made famous by the text Design Patterns by Gamma Helm et al devdaily com 49 1 7 A sample process Factory pattern example e The code and diagram that follow demonstrate a small simple example of the Factory pattern public abstract class Dog public abstract void speak public class Poodle extends Dog public void speak 4 System out println The poodle says arf public class SiberianHusky extends Dog public void speak 4 System out println The husky says Whazzup public class Rottweiler extends Dog public void speak System out println The Rottweiler says in a very deep voice WOOF devdaily com 50 1 7 A sample process public class Main Y public Main create a small dog Dog dog DogFactory getDog smal1 dog speak create a big dog dog DogFactory getDog big dog speak create a working dog d
34. business case including alternatives for risk man agement staffing project plan and trade offs between cost schedule and profitability e Develop a candidate architecture Artifacts e A vision document e A use case model survey e An initial project glossary An initial business case e An initial risk assessment e A project plan Other possible items An initial use case model An initial domain model One or more prototypes devdaily com 26 1 6 The Rational Unified Process RUP 1 6 2 Elaboration The The Rational Unified Process An Introduction 9 specifies the follow ing purpose objectives activities and outcome from an elaboration phase Purpose e Analyze the problem domain e Establish a sound architecturla foundation Develop the project plan e Eliminate the highest risk elements Objectives e Define validate and baseline the architecture e Baseline the vision e Baseline a plan for the construction phase e Demonstrate that the baseline architecture will support the vision for a reasonable cost in a reasonable time or not Activities e The vision is elaborated e The process infrastructure and development environment are elabo rated e Processes tools and automation support are put into place e The architecture is elaborated and the components are selected Outcome Deliverables e An 80 complete use case model has been developed e
35. ce of Java code that evaluates to some thing or some value e Example lt 2 2 gt evaluates to 4 e Expressions are evaluated at request time 3 13 6 Declarations e Use lt gt syntax for declarations e Use declarations to declare class scope variables and methods 3 13 7 Directives e Use lt 0 gt syntax for declarations e Use directives to declare information needed by the JSP engine e Directives include page include and taglib page directive e lt page contentType text html gt e Lets the developer specify packages to include e Lets the developer specify more advanced page features devdaily com 131 3 13 JavaServer Pages request Represents the HTTP request as received by the server response Represents the HTTP response to be send by the server out Print Writer object that is used to write to the response err poop Figure 3 1 List of implicit JSP objects taglib directive e lt 0 taglib uri uriToTaglib prefix someID gt e Lets the developer include tag libraries e Tag libraries are generally powerful reusable components for web de velopers e Tag libraries can be created by local developers are available open source or can be purchased include directive e lt 0 include file filename jsp gt e Lets one JSP include another JSP or HTML document The JSP container reads the included file and creates on servlet e Includes occur at
36. com 116 3 4 Threads 3 4 7 Thread references e The Java Programming Language excellent chapter on threads e Sun s Java Tutorial at http java sun com docs books tutorial or more specifically http java sun com docs books tutorial essential threads index html devdaily com 117 3 5 JavaBeans 3 5 JavaBeans e A JavaBean is a reusable software component based on Sun s Jav aBeans specification that can be visually manipulated in a builder tool A JavaBean is simply a Java class that has get and set methods for each class attribute These get and set methods follow a standard naming convention A set of properties that can be read changed or discovered May be serializable e May generate or listen to events devdaily com 118 3 6 Remote Method Invocation RMI 3 6 Remote Method Invocation RMI Allows Java programs to call methods on Java objects in different virtual machines and even different physical machines e An RMI server is a java class that is registered in the JVM The JVM listens on a dedicated port for RMI requests RMI clients call the server through a proxy that implements the same interface as the server The Java SDK contains the rmic compiler to automatically generate the proxy and server code required to make a class an RMI server 3 7 Java Native Interface JNI e Lets you run C programs from Java A great feature if you have a large amount of high qua
37. ct supports a public toString method that takes no param eters and returns a String object that method is invoked whenever a or expression has an object of that type where a String object is expected e All primitive types are implicitly converted to String objects when used in String expressions 2 8 16 Native Methods e Used when you need to manipulate some hardware directly or execute code not written in Java e Portability and safety of the code are lost e Implemented using an API provided by the people who wrote the virtual machine on the platform where the code will run devdaily com 89 2 8 Classes and objects e The standard API for C programmers is called Java Native Interface IND e Other API s are being defined for other languages devdaily com 90 2 9 Methods and parameters 2 9 Methods and parameters 2 9 1 Methods e Methods in Java define the behavior of the class e Methods are similar to procedures or subroutines in other languages e The real benefits of object orientation come from hiding the imple mentation of a class behind its operations e Methods access the internal implementation details of a class that are hidden from other objects e Hiding data behind methods is so fundamental to object orientation it has a name encapsulation e Methods have zero or more parameters e A method can have a return value e A method s statements appear in a block of curly braces
38. ds a Set Cookie header in a re sponse The browser sends the server the cookies back in the request headers The server is only sent the cookies for its domain Many web application platforms JSP servlets ASP use cookies for session tracking Cookies have expiration dates after which they are no longer sent to the server The total cookie header may not exceed 4K and client sofware may have more restrictions Due to security concerns some users turn off cookies in their browsers devdaily com 126 3 11 Servlets and JSPs 3 11 Servlets and JSPs 3 11 1 Objectives Describe the JSP dynamic HTML model Write JSPs to generate dynamic HTML Include Java code in JSPs Understand and use implicit objects in JSPs 3 11 2 Introduction Background Original HTML content on the web was largely static HTML pages CGI scripts were the first way of generating HTML pages with dynamic content Servlets are Java programs that run within a web server or within a web application server There is a special Servlet API Servlets work hand in hand with databases JavaBeans compo nents and JSPs JSPs are a combination of HTML and Java code JSPs are a form of servlets that is they are compiled into servlets behind the scenes In practice however they appear quite different and appear like a combination of HTML and Java code In practice JSPs should be approximately 90 HTML code and 10 Java code de
39. e sleep is invoked thread calls wait thread is blocking on I O e dead the end of the run method has been reached devdaily com 115 3 4 Threads 3 4 4 Creating a threaded class with thread Extend the java lang Thread class and override its run method The run method defines the behavior of the thread while it is run ning When the run method ends the thread goes into the dead state As a developer you call the start method of the thread the JVM calls the run method Never call the run method directly 3 4 5 Creating a threaded class with the runnable interface Cannot always extend the Thread class because of single inheritance Implement the java lang Runnable interface must implement the run method Include a Thread attribute in the class The run method still defines the behavior of the thread while it is running 3 4 6 Thread methods sleep long ms causes the thread to sleep for the specified number of milliseconds yield provides a hint to the scheduler that this doesn t have to run at the current time so the scheduler can choose another thread to run if need be join used to let one thread wait for another to terminate interrupt used to request that the thread cancel itself notifyAl1 wakes up all waiting threads wait used to pause the thread presumably while it waits for some condition to be satisfied devdaily
40. e O e getContentType 3 12 7 HTTPServletResponse e getWriter e setContentType e getOutputStream devdaily com 129 3 13 JavaServer Pages 3 13 JavaServer Pages e What is a JSP e Why use JSPs Directives Scriptlets Actions 3 13 1 What is a JSP e JSPs are a combination of HTML code and Java code e JSP files usually have a filename extension of jsp e JSP files are compiled into Servlets by the JSP container Provides automatic session management Implicit programming objects are available including request response and others JavaBeans are the component model 3 13 2 JSP engine container e Compiles a JSP page into a servlet once the first time it is called e Eexecutes the servlets service method e Sends the resulting text back to the caller 3 13 3 Translation time and request time e Translation time the time a JSP is compiled into a Servlet e Translation time certain JSP elements are evaluated at translation time e Request time the time a JSP is requested by a user e Request time some JSP elements such as expressions are evaluated at request time devdaily com 130 3 13 JavaServer Pages 3 13 4 Scriptlets e Use lt gt syntax to include Java code directly into the JSP e Any valid Java code can be included 3 13 5 Expressions e Use lt gt syntax to include expressions into a JSP e An expression is a pie
41. eate a Statement object and then execute it using the proper execute method For SELECT statements use executeQuery For statements that create or modify tables use executeUpdate e Example Statement stmt conn createStatement String query SELECT username password FROM user ResultSet rs stmt executeQuery query while rs next String user rs getString username String password rs getString password System out println Username user System out println Password password devdaily com 139 4 1 Databases and JDBC 4 1 4 getXXX methods With ResultSet objects e getByte e getShort e getInt e getLong e getFloat e getDouble e getBigDecimal e getBoolean e getString e getBytes e getDate e getTime e getTimestamp e getAsciiStream e getUnicodeStream e getBinaryStream e getObject 4 1 5 Updating the database Use executeUpdate when using SQL UPDATE commands String update UPDATE user SET password bar WHERE user foo stmt executeUpdate update devdaily com 140 4 1 Databases and JDBC 4 1 6 PreparedStatements e Developers often use PreparedStatements because the syntax is eas ler e Example PreparedStatement update conn prepareStatement UPDATE user SET password WHERE user 7 updateSales setString 1 bar updateSales setString 2 foo e Intended for most useful and high performance
42. ects e A class defines the attributes and behaviors an object will have e An object is a specific instance of a class e If an object has no attributes is it really a valid object Attributes e A data variable with object scope e Examples book attributes title author publisher ISBN The value of an object s attributes define its state Attributes should not be accessible to entities outside the object If an object has no attributes is it really a valid object Behaviors e Method a function with object scope e Methods can operate on that object s attributes e Defines the objects behaviors how it does what it does e Methods define the objects responsibilities If an object has no methods is it really a valid object devdaily com 31 1 7 A sample process Discover classes Work outward from data requirements to build a static model Jump start with grammatical inspection Make a quick pass through the available material making lists of the nouns verbs and possessive phrases Nouns become classes Noun phrases becomes class attributes Verbs become operations behaviors and associations Possessive phrases may indicate that nouns should be attributes rather than objects Create this list of class candidates Best sources of classes high level problem statement lower level re quirements expert knowledge of the problem space Go through the candidate classes and elimina
43. ecuted repeatedly until its boolean expression eval uates to false e A while loop will execute zero or more times e The boolean expression can be any expression that returns a boolean value while boolean expression statement e A do while loop executes at least once do statement while boolean expression devdaily com 78 2 7 Flow control and loops 2 7 7 for e Used to loop over a range of values from beginning to end for init expr boolean expr incr expr statement e Typically used to iterate a variable over a range of values char ch new char s length for int i 0 i lt s length i ch i s charAt i 2 7 8 Labels e Statements can be labeled e Typically used on blocks and loops label statement 2 7 9 break e Used to exit from any block not just a switch e Most often used to break out of a loop e An unlabeled break terminates the innermost switch for while or do while e To terminate an outer statement label the outer statement and use its label name in the break statement 2 7 10 continue e Skips to the end of a loop s body and evaluates the boolean expression that controls the loop devdaily com 79 2 7 Flow control and loops e Has meaning only inside loops while do while and for e A labeled continue will break out of any inner loops on its way to the next iteration of the named loop 2 7 11 return e Terminates execution of a met
44. ed class An extended class can be used wherever the original class was legal Polymorphism an object of a given class can have multiple forms The extended class is a subclass The class it extends is the superclass If a class does not explicitly extend a class then it implicitly extends Object Object declares methods that are implemented by all objects devdaily com 94 2 10 Extending Classes 2 10 4 lt A simple example e A simple example of extending a base Animal class public abstract class Animal protected boolean hasColdNose public abstract String speak public void setHasWetNose boolean hasColdNose this hasColdNose hasColdNose public boolean hasColdNose return hasColdNose public class Dog extends Animal public Dog hasColdNose true public String speak 4 return woof public class Bird extends Animal public Bird hasColdNose false public String speak return chirp devdaily com 95 2 10 Extending Classes public class Main public Main f Animal fido new Dog Animal bigbird new Bird System out println fido says fido speak System out println bigbird says bigbird speak public static void main String args new Main 2 10 5 What protected really means e A protected class member can be accessed by classes that extend that class e A protected class member al
45. ents are created e Elaboration the product vision and architecture are defined con struction cycles are planned e Construction the software is taken from an architectural baseline to the point where it is ready to make the transition to the user commu nity e Transition The software is turned into the hands of the user s com munity devdaily com 24 1 6 The Rational Unified Process RUP 4 Phases 9 Disciplines mception Elaboration Construction Transition Business Strateg User Experience system Analysis _ Implementation configuration and hange Mgmt Project Management Environment i Elab Elab nst Const Const ran Tran Anitai HL A2 OA DAN Iterations Figure 1 9 A high level view of the Rational Unified Process Image cour tesy of Rational Software 1 6 1 Inception phase The The Rational Unified Process An Introduction 9 specifies the fol lowing objectives activities and artifacts from an inception phase Objectives e Establish project s scope and boundary conditions e Determine the critical uses of the system e Exhibiting at least one candidate architecture against some of the primary scenarios Estimating the overall cost and schedule for the entire project Estimating potential risks devdaily com 25 1 6 The Rational Unified Process RUP Activities e Formulate the scope of the project e Plan and prepare the
46. erface for using XML in Java programs There are several implementations of this API including Xerces from the Apache Group and Crimson from Sun 3 14 2 XSLT eXtensible Stylesheet Language Transformation XSLT documents are instructions that describe how to transform one XML document into another type of XML document Example uses Converting the XML for an order into HTML that displays the order to the user Converting an XML invoice from a vendor s system into XML that your internal system understands This sample shows how to transform the sandwich XML from the previous section into HTML Input XML lt xml version 1 0 encoding UTF 8 gt lt sandwich price 2 00 gt devdaily com 135 3 14 Survey of other server side Java technologies lt meat gt Pastrami lt meat gt lt bread gt Rye lt bread gt lt cheese slices 1 gt Swiss lt cheese gt lt sandwich gt XSLT lt XSLT is itself XML gt lt xml version 1 0 encoding UTF 8 gt lt xsl stylesheet version 1 0 xmlns xsl http www w3 org 1999 XSL Transform gt lt xsl template match sandwich gt lt the HTML tags are embedded directly in the template gt lt html gt lt head gt lt title gt My Sandwich lt title gt lt head gt lt body gt lt when executed the value of element is replaced with the actual value gt lt b gt Meat lt b gt lt xsl value of select meat gt lt br gt lt
47. eritance Show how to implement an interface Describe the differences between interfaces and abstract classes 2 11 3 An example interface Java has single inheritance of implementation you can extend only one class Java has multiple interface inheritance All methods in an interface are implicitly abstract Each class that implements the interface must implement all its meth ods Methods in an interface are always public Fields in an interface are always static and final Nested classes and interfaces Nested classes and interfaces let you associate types that are strongly related to an interface inside that interface Any class or interface inside an interface is public Any classes nested inside an interface are also static devdaily com 102 2 11 Interfaces e Any interface nested inside a class can be public protected package accessible or private 2 11 4 Single inheritance versus multiple inheritance e A new class can extend exactly one superclass e The new class inherits the superclass s a contract and b implemen tation e Some languages allow multiple inheritance two or more superclasses e Problem of multiple inheritance arises from multiple inheritance of implementation Usually related to a class that maintains state in formation 2 11 5 Extending Interfaces e Interfaces can be extended using the extends keyword e Interfaces can extend more than one interface i
48. fecycle 113 33 0 URL stas be tee Ae a are lew ad 114 devdaily com 4 Contents 3 4 3 5 3 6 3 7 3 8 3 9 3 10 3 11 3 12 3 13 3 3 6 URLConnection 200 4 114 Threads o tae Be eo BRAS RB Po le we ea a 115 3 4 1 Objectives 22 ee ab bee ee ead ew eee eS 115 3 4 2 Applications without multiple threads 115 3 43 Thread states ooo 115 3 44 Creating a threaded class with thread 116 3 4 5 Creating a threaded class with the runnable interface 116 3 4 6 Thread methods 116 3 4 7 Thread references 2 2 0004 117 JavaBeans 344 22 465 eae bE a a aa 118 Remote Method Invocation RMI 119 Java Native Interface JNI 119 Collections framework 2 0 00 00 eee 120 ror sists vss peters By Bale ee SS Bee BY 121 SiOr2 MAPS ssa Sa A fet BAGO A a 122 3 8 3 Collection Utilities o 122 Internationalization localization and formatting 124 HTTP protocol si iaoa a kea eR ee a 125 3 10 1 Request and Response 125 3 10 2 COOKIES roe aa E A da 126 Servlets and JSPS o 127 3 11 1 Objectives e 127 3 11 2 Introduction Background 127 Servlets 2 dG se hos noe ag wn o s Oh oon ae POA 128 121 Ob echives s cr o Poke as ee we Roto 128 3512 2 Servlets basies a ap nese De eee ate Bee 2 128 3 1
49. g inches feet and pounds while the other used metric units for a key spacecraft operation This information was critical to the maneuvers required to place the spacecraft in the proper Mars orbit 4 2 3 USS Yorktown An article in the November 1998 Scientific American describes an incident aboard the USS Yorktown a guided missile cruiser A crew member mis takenly entered a zero for a data value which resulted in a division by zero an error that cascaded and eventually shut down the ship s propulsion sys tem The Yorktown was dead in the water for a couple of hours because a program didn t check for valid input 4 2 4 Types of tests We can t tell the story of working backwards using JUnit until we see how and why we should use tools like JUnit So first a little background on testing e Unit tests An automated exercise of code where the developer may create an artificial environment to automatically exercise a unit of code e Regression tests Running the same set of tests regularly or after known events e Black Box tests Testing based only upon the documentation of the unit without any knowledge of the implementation devdaily com 143 4 2 JUnit e White Box tests Tests based on knowledge of the internals of the unit Integration tests Taking separate units of software that have al ready been tested and testing them together e Bounds tests Testing the outer ranges of values Nu
50. ges get Bob if we have a user named Nicole what s her age if userAges containsKey Nicole Integer nicolesAge Integer userAges get Nicole e Caution If the key object is mutable take care not to change its value after using it in a Map e There are several Map implementations including HashMap and Hashtable e Asa Java 1 1 legacy class Hashtable is syncronized for thread safety 3 8 3 Collection Utilities e The java util Collections class provides standard utilities for Collec tions List Sorting Binary List Search List reversing and shuffling Min and Max Synchonization devdaily com 122 3 8 Collections framework e Sorting makes use of the Comparator interface which a programmer implements to determine how objects of a particular type are to be ordered e The Syncronization methods return thread safe collections that are backed by a specified collection Note that iteration is still not thread safe in this case devdaily com 123 3 9 Internationalization localization and formatting 3 9 Internationalization localization and format ting e Locale a specific place cultural political or geographical e Objects can localize their behvior to a user s expectations locale sensitive object e ResourceBundle methods to look up resources in a bundle by a string key devdaily com 124 3 10 HTTP protocol 3 10 HTTP protoco
51. gives up on the message if the receiving object is not ready to accept it 3 Timeout sending object waits only for a certain time period for the receiving object to be ready to accept the message 4 Asynchronous sender can send a message to a receiver regardless of whether the receiver is ready to receive it devdaily com 13 1 4 UML summary 1 4 UML summary Unified Modeling Language UML A modeling language not a method Provides a graphical representation that allows developers and archi tects to model a software system before the system is ever built Analogy an architect creating a blueprint before a house or office building is ever built The UML does not specify a methodology process Therefore saying We use the UML methodology is incorrect A few URLs for reference http www omg org http www rational com uml index jsp UML Distilled http www awl com cseng titles 0 201 32563 2 1 4 1 Standard diagrams The UML defines nine standard diagrams Use Case Class Interaction 1 Sequence 2 Collaboration Package State Activity Component Deployment Note that the UML can be used to model other processes besides software development devdaily com 14 1 4 UML summary SiteVisitor Use Cases SiteVisitor Member Figure 1 1 A sample UML Use Case Diagram Use Case diagram A typical interaction between a user and a computer system Class di
52. here Runs on any platform with a JVM Windows Unix Linux Apple AS 400 cell phones desktop sets Interpreted Java bytecode is portable Multithreaded much easier to write multithreaded programs Dynamic classes are loaded as needed High performance just in time compilers advanced memory man agement makes Java programs faster 2 1 3 What is Java A very portable object oriented programming language A large supporting class library that covers many general needs Can creates Applets Applications Servlets JavaServer Pages and more An open standard the language specification is publicly available JVM Java Virtual Machine 2 1 4 How where to get Java http java sun com IBM A variety of IDE s Integrated Development Environments Borland JBuilder devdaily com 62 2 1 Introduction IntelliJ IDEA IBM Visual Age for Java Symantec BEA Visual Cafe Open Source Netbeans More devdaily com 63 2 2 First Steps with Java 2 2 First Steps with Java 2 2 1 Java Commands and Utilities e javac the Java compiler e java the Java bytecode interpreter JVM e appletviewer lets you view applets without a browser e jdb the Java debugger e javadoc a utility that lets you generate documentation from your Java source code and the Javadoc comments you place in your source code e jar Java archive utility similar to
53. hod and returns to the invoker e Ifthe method has a return type the return must include an expression of a type that could be assigned to the return type public static double absolute double val if val lt 0 return val else return val 2 7 12 No goto Statement e No goto construct to transfer control to an arbitrary statement in a method e Primary uses of goto in other languages Controlling outer loops from within nested loops Java provides labeled break and continue Skipping the rest of a block of code that is not in a loop when an answer or error is found Use a labeled break Executing cleanup code before a method or block of code exits Use a labeled break or the finally construct of the try statement devdaily com 80 2 8 Classes and objects 2 8 Classes and objects 2 8 1 Introduction e Class the fundamental unit of programming in Java e Classes contain the attributes and behaviors of the objects you will create e Classes define how an object should be created how it should be de stroyed and how it should behave during it s existence 2 8 2 Objectives Upon completion of this section you should be able to e Define the difference between a Java class and an object e Create a simple Java class e Create constructors for your classes e Define the behavior of your classes e Be able to describe Java s garbage collection process e Declare and initialize ins
54. ic Where you capture business rules and application logic e Not necessarily meant to endure as stand alone classes as you proceed e Sometimes serve as placeholders to make sure you don t forget any functionality and system behavior required by your uses cases Performing robustness analysis e Actors can talk only to Boundary objects e Boundary objects can talk only to Controllers and Actors e Entity objects can only talk to Controllers e Controllers can talk to both Boundary objects and Controllers but not to Actors e Update your static model Milestone 2 Preliminary Design Review devdaily com Al 1 7 A sample process 1 7 4 Interaction modeling Introduction Current state e Uncovered most problem space objects and assigned some attributes to them e Defined some static relationships between these objects e Defined a few dynamic relationships on robustness diagrams Interaction modeling is the phase in which you build the threads that weave your objects together and enable you to see how they will perform useful behavior One of the primary tools of this task is creating sequence dia grams Objectives Upon completion of this section students will be able to e Define the goals of interaction modeling e Create sequence diagrams e Put behavioral methods on your classes e Update your static model Goals of Interaction Modeling e Allocate behavior among entity boundary and control objec
55. iew devdaily com 39 1 7 A sample process 1 7 3 Robustness analysis Robustness analysis involves 1 analyzing the text of each of your use cases 2 identify a first guess set of objects that will participate in the use case then 3 classify these objects into a Boundary objects b Entity objects c Control objects 4 This has parallels in the Model View Controller paradigm Definitions e Boundary objects Actors use these to communicate with the sys tem View e Entity objects Usually objects from the problem domain Model e Control objects Serve as the glue between Boundary and Entity objects Controller Key roles of robustness analysis e Sanity check make sure your use case text is correct e Completeness check make sure your use cases address all the neces sary alternate courses of action e Ongoing discovery of objects you may have missed some objects during domain modeling Closer look at object types Boundary objects e View e Objects that the Actors will be interacting with e Windows screens dialogs menus e Get many from prototypes devdaily com 40 1 7 A sample process Entity objects e Model e Often map to database tables and files e Many come from the domain model e Simpler and more generic easier to reuse in other projects Control objects e Controller Embody much of the application log
56. iness misunderstood e Business changes e False feature rich e Staff turnover 1 10 2 Four Variables In the XP model there are four control variables in software development 1 Cost 2 Time 3 Quality 4 Scope Customers and managers get to pick the values of any three of the variables devdaily com 55 1 10 Introduction to Extreme Programming 1 10 3 The Cost of Change Under certain circumstances the exponential rise in the cost of changing software over time can be flattened If the cost curve can be flattened old assumptions about the best way to develop software no longer hold true Several factors make code easy to change even after years of production 1 A simple design 2 Automated tests 3 Lots of practice in modifying the design 1 10 4 Four Values 1 Communication 2 Simplicity 3 Feedback 4 Courage 1 10 5 Basic Principles 1 Rapid Feedback 2 Assume simplicity 3 Incremental change 4 Embracing change 5 Quality work 1 10 6 Back to Basics 1 Coding 2 Testing 3 Listening 4 Designing devdaily com 56 1 10 Introduction to Extreme Programming 1 10 7 The Solution 1 The Planning Game Business people get to decide e Scope e Priority e Composition e Dates of releases Technical people get to decide e Estimates e Consequences e Process e Detailed scheduling 2 Small Releases 3 Metaphor 4 Simple Design 5 Testing 6 Refactoring 7 Pair Programming
57. ing I want to be able to do is to get a list of toppings that a pizza has so I write a little code like this public void testToppingsOnNewPizza Pizza pizza new Pizza List toppings pizza getToppings assert toppings size 0 5 Run this JUnit test Does it work 6 No it doesn t work because the getToppings method does not exist So what do you do next Make it work Implement this behavior in the Pizza class 7 Goto the Pizza class Create a method named getToppings From what we know so far it should return a List and apparently for a new Pizza the best thing to do is to return an empty List not a null but a List with nothing in it public List getToppings return this toppings 8 Will this work by itself No you also have to have a List named toppings in the Pizza class Here s what the Pizza class should look like public class Pizza devdaily com 146 4 2 JUnit private List toppings new LinkedList public List getToppings return this toppings 9 Now run JUnit again does the test work 4 2 9 Recap Whoa that went fast how about a recap No problem Here s what we did 1 Write one test 2 Compile the test It should fail because you haven t implemented anything yet 3 Implement just enough to compile Refactor first if necessary 4 Run the test and see it fail 5 Implement just enough to make the test pass
58. ion returns a URLConnection 3 3 6 URLConnection e Created from a URL object using openConnection URL url new URL http www devdaily com URLConnection uc url openConnection e getInputStream read data from the server e getContentType returns the MIME content type of the data e getContentLength returns the number of bytes in the content devdaily com 114 3 4 Threads 3 4 Threads 3 4 1 Objectives e Explain what threads are how they work and when to use them e Create threads using the Thread class Create threads using the Runnable interface e Describe thread states Understand the methods that are used when manipulating threads 3 4 2 Applications without multiple threads e Many applications work without multiple threads of concurrency e In this world a sequence of actions is completed in a linear one thread of thought at a time manner e Java makes it easy for developers to create multiple threads that es sentially run simultaneously How this really works depends on what operating system your application is running on e A thread is considered lightweight because it runs within the context of a full blown program 3 4 3 Thread states e new an empty thread with no system resources allocated all you can do is start it e runnable the start method is called and the thread is not dead or in the not runnable state e not runnabl
59. ion modeling 42 1 7 5 Collaboration and State Modeling 45 1 7 6 Addressing Requirements 47 Contents 1 7 7 Survey of Design Patterns 49 1 8 Agile Methods o e 53 1 9 The Agile Alliance o e 53 1 10 Introduction to Extreme Programming 55 1 10 1 Risk The Basic Problem 55 1 10 2 Four Variables vii uea aa a ie E a a a i a 55 1 10 3 The Cost of Change ao aoaaa a 56 1 10 4 Four Values oaaae 56 1 10 5 Basic Principles saaara ny amm a eh a eg BS 56 11076 Back to Basics qo 5 sche a a a 56 110 7 The Solution 2 6 iaa ara a BS 57 LAT OO Summary a eee le ae eek ee eee a 58 LALA OO Concepts e wi keke s hid ela ce eal we es 58 BIR IMT gs it Stele beh ee tg ad Blan la 58 2 Day 2 The Java Programming Language 61 Dl AntroductiGns 2 a ri Ee 61 2 1 1 Chapter Objectives o 61 2 1 2 Java design goals 62 2 1 3 What is Java o 62 2 1 4 How where to get Java 62 2 2 First Steps with Java e 64 2 2 1 Java Commands and Utilities 64 2 2 2 A first application 64 PASS MAIN 3 ares A eects ete cA he Moe oot be ON 65 2 3 Variables constants and keywords 66 2 3 1 Primitive data types 0 66 2 3 2 gt iteralse ei ae ethe
60. ional The system shall automatically generate postings to the general ledger e Data The system international currencies e Performance The system must in XX seconds e Capacity Up to 10 000 transactions per day e Test Stress testing shall XX users YY computers Use Cases and Requirements e A use case describes a unit of behavior e A requirement describes a law that governs behavior e Several types of requirements functional performance and constraints e A use case can satisfy one or more functional requirements devdaily com A7 1 7 A sample process A functional requirement may be satisfied by one or more use cases Requirements are requirements use cases are use cases Requirements are not use cases Requirements Traceability Make a list of the system requirements Write the user manual for the system in the form of use cases Iterate with your customers until you have closure of items 1 and 2 Make sure you can trace every piece of your design to at least one user requirement Make sure you can trace every requirement to the point at which its satisfied within your design Trace your design back to your requirements as you review the design during your critical design review devdaily com 48 1 7 A sample process 1 7 7 Survey of Design Patterns e Repeating patterns Her garden is like mine except that in mine 1 use astil
61. l e Underlying protocol for all Web Browser Web Server communication whether static or dynamic e Uses request and response communication model e Cookies 3 10 1 Request and Response e Client issues a request to the server e Server processes the request and responds to the client e The GET verb asks the server for the content at a given URL The client may specify extra parameters for the server These query param eters can be seen on the URL in the browser http www yahoo com search q java e The POST verb sends data to the server to be processed This data is packaged in the request a well defined format and is not visible in the browser The server responds in the same way as with GET requests e Headers are name value pairs that precede the request or response data These can indicate such informations as what type of data is being sent how long it is and what type of client server is doing the sender e Example At the command prompt telnet www google com 80 When connected type exactly GET index html HTTP 1 1 Hit enter twice this sends the request Note the response code 200 OK means the server processed the request successfully Note the headers Content Type Content Length a cookie and the web server type devdaily com 125 3 10 HTTP protocol 3 10 2 Cookies Simple name value pairs used to store state on the client Cookies are set when the server sen
62. l and loops e Local variables exist only as long as the block containing their code is executing e Braces group zero or more statements into a block 2 7 4 if else e Basic form of conditional control flow if boolean expression statementi else statement2 e Example class IfElsel public static void main String args int i 10 if i 1 System out println i 1 else if i 2 System out println i 2 else if i 3 System out println i 3 else System out println don t know what i is 2 7 5 switch e Evaluates an integer expression in the switch statement e Transfers control to an appropriate case label e If no match is found control is transferred to a default label e If there is no default label and no other match is found the switch statement is skipped devdaily com 77 2 7 Flow control and loops A break statement is usually used at the end of each case If a break is not used control flow falls through to the next case All case labels must be constant expressions The value that you are switching on must be byte short char or int Example switch verbosity case BLATHERING System out println blah blah blah my name is case NORMAL System out println What is your name case TERSE System out println Yo break default System out println Hello 2 7 6 while and do while e A while loop is ex
63. l requirements are created e Elaboration the product vision and architecture are defined con struction cycles are planned e Construction the software is taken from an architectural baseline to the point where it is ready to make the transition to the user commu nity e Transition The software is turned into the hands of the user s com munity Agile Methods e Our highest priority is to satisfy the customer through early and con tinuous delivery of valuable software e Welcome changing requirements even late in development Agile pro cesses harness change for the customer s competitive advantage e Deliver working software frequently from a couple of weeks to a couple of months with a preference to the shorter timescale e Business people and developers must work together daily throughout the project e Build projects around motivated individuals Give them the environ ment and support they need and trust them to get the job done e The most efficient and effective method of conveying information to and within a development team is face to face conversation e Working software is the primary measure of progress devdaily com 59 1 11 OO Summary e Agile processes promote sustainable development The sponsors de velopers and users should be able to maintain a constant pace indefi nitely e Continuous attention to technical excellence and good design enhances agility
64. lic class ChildClass extends ParentClass public ChildClass System out println ChildClass constructor was called public class Main public static void main String args ChildClass cc new ChildClass 2 10 7 Overriding methods hiding fields and nested classes Overloading providing more than one method with the same name but with different signatures Overriding replacing a superclass s implementation with your own devdaily com 97 2 10 Extending Classes Overriding e Signatures must be identical e Return type must be the same e Only accessible non static methods can be overridden e A subclass can determine whether a parameter in an overridden method is final The super keyword e Available in all non static methods of a class super method uses the superclass s implementation of method 2 10 8 Marking methods and classes final e No extended class can override the method to change its behavior This is the final version of that method e A class marked final cannot be extended by any other class and all the methods of a final class are implicitly final e Security anyone who uses the class can be sure the behavior will not change validatePassword example e Serious restriction on the use of the class e Final simplifies optimizations 2 10 9 The object class e All classes inherit from Object e Object s methods fall in two classes utilities
65. lity C code already written and want to leverage that for new Java applications Can also be used if maximizing the speed of the code is critical e When using JNI you may be limiting the portability of your applica tion devdaily com 119 3 8 Collections framework 3 8 Collections framework e The java util package provides interfaces and implementations for stan dard data structures e Collection is the base interface for all collection types with methods for adding removing and counting elements e Iterator Interface for iterating over a collection e The collections have a single element type Object This has two side effects Primitives such as int char and boolean cannot be placed in col lections without using their object wrappers Integer Character Boolean It is up to the programmer to keep collections consistent since one can add objects of multple types to a collection e Unless explicitly specified in the documentation assume Collection implementations are NOT thread safe Why use the unsafe implemen tations at all Because unless you really are sharing the collections among threads they will be considerably faster than the thread safe versions e Basic collection usage Collection stuff new HashSet String kiwi Kiwi stuff add Apple stuff add Drange stuff add kiwi Iterator it stuff iterator while it hasNext devdaily com 120 3 8
66. lls zeroes blanks etc e Stress tests Testing a system s ability to handle a desired system load typically more than is expected System Acceptance testing Making sure the software as a whole works as expected 4 2 5 Unit Testing 101 Definitions of unit testing A few definitions of unit tests from various sources e A unit test is an automated exercise of code e A unit test is written for each module class in isolation to verify its behavior e Unit tests are tests that you the developer create to exercise your code and prove that it works i e prove that each of your methods meet the criteria of its contract e Unit testing is a form of white box testing e In combination unit tests can be used to create large regression tests C3 the famous Chrysler C3 project has over 1300 unit tests performing over 13 000 individual checks They run in about 10 minutes 4 2 6 Goals of unit testing e Test each part unit of the code in isolation e Create tests that retain their value over time e Create much larger regression tests that help demonstrate that the entire system still works or not after changes devdaily com 144 4 2 JUnit e In the XP view if a program feature lacks an automated test it is assumed that it doesn t work e In a team environment unit tests ensure that we don t break one an other s code 4 2 7 Unit Testing with JUnit How to create unit tes
67. minates the need to free objects explicitly This eliminates a common cause of errors in C C and other lan guages memory leaks Never have to worry about dangling refer ences When an object is no longer reachable the space it occupies can be reclaimed Space is reclaimed at the garbage collector s discretion Creating and collecting large numbers of objects can interfere with time critical applications finalize A class can implement a finalize method This method will be executed before an object s space is reclaimed Gives you a chance to use the state of the object to reclaim other non Java resources finalize is declared like this protected void finalize throws Throwable The eh F Important when dealing with non Java resources such as open files Example a class that opens a file should provide a close method Even then there is no guarantee that the programmer will call the close method so it should be done in a finalize method public void close if file null file close devdaily com 88 2 8 Classes and objects file null protected void finalize throws Throwable try close finally super finalize e The close method is written carefully in case it is called more than once e super finalize is called to make sure your superclass is also finalized e Train yourself to always do this 2 8 15 The toString Method e Ifan obje
68. ne ee ke ie ee EKE dei 66 2 33 Constants 82h pins ket Pe a ae ds ba 67 2 3 4 Reserved keywords 2 0004 68 DA ATTAYS caia kA EA a ee ee aaa ee 69 2 5 SHINES ssa a She ae es oa eS Sea a 70 2 5 1 String objects ae ieee ae a a 70 2 5 2 StringBuffer class sae 64 phe ee e h 70 2 6 Comments and Javadoc oaoa 72 2 6 1 Types ofcomments 20004 72 2 6 2 Javadoc comment tags ooo 72 2 6 3 A comment example 74 2 6 4 Notes on Usage o o 0084 74 2 7 Flow control and loops o a 76 devdaily com 2 Contents 2 fl Introduction cores oa p iae Qk a 76 26 2 ODIECHIVES e ra aa e Qe a es 76 2 7 3 Statements and blocks 76 2A E A ee won 77 PATAT Sswitchy 25 vos A ae ae a ee SR 77 2 7 6 while and do while 78 Blt MOT ee tro ees A hd ee oe RS Be ERROR 79 28 gt EIDES 4208s od che BOR atte Rites Lae Se ae ae oe 79 ES A E ad eel en oh Tet Be ee ee 79 2 7 10 Continue ce oe ka A a a 79 2 611 returns og bee So a a a 80 2 7 12 No goto Statement o 80 2 8 Classes and objects ee 81 2 821 Introduction a ir BS 81 2 82 ODIEChIVES 0 1 o AA A ae ae i 81 2 8 3 A Simple Class 0 81 A A A cid Be Sy bed hee Bet Be ee a 82 2 8 5 Access Control and Inheritance 82 2 8 6 Creating Objects 200 83 2 8 Constr ctors oo 6 24 4
69. nterface Shimmer extends FloorWax DessertTopping ldots e All methods and constants defined by FloorWax and Dessert Topping are part of Shimmer Name Conflicts e A class or interface can be a subtype of more than one interface e What happens when a method of the same name appears in more than one interface 2 11 6 Implementing Interfaces e Most interfaces may have several useful implementations e Enumeration is an interface devdaily com 103 2 11 Interfaces 2 11 7 Using an Implementation e Use an implementing class just by extending it e Can also use a technique called forwarding create an object of an implementing class and forward all the methods of the interface to that object 2 11 8 Marker Interfaces e Do not declare any methods mark a class as having some general property e Define no language level behavior e All of the contract is in the documentation 2 11 9 When to Use Interfaces Two Important Differences Between Interfaces and Abstract Classes e Interfaces provide a form of multiple inheritance A class can extend only one other class e Interfaces are limited to public methods and constants with no im plementation Abstract classes can have a partial implementation protected parts static methods etc Interface or Abstract Class e These two differences usually direct the choice e If multiple inheritance is important or even useful interfaces are used e Abstract class
70. og DogFactory getDog working dog speak public static void main String args new Main public class DogFactory public static Dog getDog String criteria if criteria equals small return new Poodle else if criteria equals big return new Rottweiler else if criteria equals working return new SiberianHusky return null devdaily com 51 1 7 A sample process creates Figure 1 11 A UML use case diagram for the DogFactory devdaily com 52 1 8 Agile Methods 1 8 Agile Methods Many developers believe that formal heavyweight processes like RUP still have significant shortcomings According the original Extreme Program ming exist 1 9 text the white book at a minimum the following roblems still Schedule slips Project canceled System goes sour Defect rate Business misunderstood Business changes False feature rich Staff turnover The Agile Alliance A set of principles from the Agile Alliance http www agilealliance org Our highest priority is to satisfy the customer through early and con tinuous delivery of valuable software Welcome changing requirements even late in development Agile pro cesses harness change for the customer s competitive advantage Deliver working software frequently from a couple of weeks to a couple of months with a preference to the shorter timescale
71. on name attrName name 2 12 4 throw e Exceptions are thrown using the throw statement e Exceptions are objects so they must be created with new before being thrown 2 12 5 The throws clause e The exceptions a method can throw are declared with a throws clause e The exceptions a method can throw are as important as the value type the method returns Choices when invoking a method that has a throws clause e Catch the exception and handle it e Catch the exception and map it to one of your exceptions by throwing an exception of a type declared in your own throws clause e Declare the exception in your throws clause and let the exception pass through your method 2 12 6 try catch and finally e Exceptions are caught by enclosing code in try blocks e The body of try is executed until an exception is thrown or it finishes successfully e If an exception is thrown each catch clause is examined in turn from first to last to see whether the exception object is assignable tto the type declared with the catch e When an assignable catch is found its code block is executed No other catch clause will be execu devdaily com 106 2 12 Exceptions e Any number of catch clauses can be associated with a try as long as each clause catches a different type of exception e Ifa finally clause is present in the try block the code is executed after all other processing in the try is complete This happens no ma
72. ouble 64 bit floating point e Samples int i 1 int age 38 float balance 1590 55 char a a boolean isTrue true 2 3 2 Literals e A literal is a vlue that can be assigned to a primitive or string variable or passed as an argument to a method call boolean literals e true e false e boolean isTrue true devdaily com 66 2 3 Variables constants and keywords char literals e An newline e lr return e t tab Floating point literals e Expresses a floating point numerical value e 3 1438 a decimal point e 1 33E 11 E or e scientific notation e 1 282F F or f 32 bit float e 1355D D or d 64 bit double String literals e A sequence of text enclosed in double quotes e String fourScore Four score and seven years ago 2 3 3 Constants e Constants are variables whose value does not change during the life of the object e Java does not have a constant keyword e In Java you define a constant like this static final String name John Jones static final float pi 3 14159 devdaily com 67 2 3 Variables constants and keywords 2 3 4 Reserved keywords e Reserved Java keywords abstract default if private throw boolean do implements protected throws break double import public transient byte else instanceof return try case extends int short void catch final interface static volatile char finally long super
73. ow message parameters on your sequence diagrams devdaily com 43 1 7 A sample process Which Methods Belong With Objects e Reusability the more general the more reusable Does this method make the class more or less reusable e Applicability is there a good fit between the object and method e Complexity is it easier to build a method in another object e Implementation knowledge does the implementation of the behavior depend on details internal to the associated method Completing Interaction Modeling e Drawn all needed sequence diagrams e Updated your static model e Last stop before you start coding Critical Design Review is essential devdaily com 44 1 7 A sample process 1 7 5 Collaboration and State Modeling Introduction e Model additional aspects of your system e Most useful in real time system design e Collaboration diagrams are similar to sequence diagrams Collaboration diagrams e Shows how critical objects collaborate within a use case e Collaboration diagrams are similar to sequence diagrams Collaboration diagrams focus on key transactions Sequence diagrams follow the flow of entire use cases emphasis on time ordering Collaboration diagrams add extra detail related to timing of mes sages State diagrams e Captures the lifecycle of one or more objects e Expressed in terms of Different states objects can assume Events that cause change
74. rally want to hide the data from programmers that will use the class e If programmers can access a class s fields directly you have no control over what values they can assign e In the Body example nextIDshould be private e If necessary you should provide get methods that allow programmers to determine the current field value and set methods to modify the value These are called accessors get and mutators set 2 8 9 this e Typically use this only when needed e Most commonly used as a way to pass a reference to the current object as a parameter to other methods devdaily com 85 2 8 Classes and objects e Often used in a case like this class Pizza String topping Pizza String topping this topping topping 2 8 10 Overloading methods e Each method has a signature e The signature is a the name together with b the number and c types of parameters e Two methods in the same class can have the same name if they have different numbers or types of parameters e This capability is called overloading e The compiler compares the number and types of parameters to find the method that matches the signature e The signature does not include the return type or list of thrown ex ceptions and you cannot overload based on these factors public void aMethod String s public void aMethod public void aMethod int i String s 1 public void aMethod String s int i 2 8 11
75. rd in the way software is developed today OOA OOD OOP is good for e Analyzing user requirements e Designing software e Constructing software Reusability reusable components Reliability Robustness Extensibility Maintainability e Reducing large problems to smaller more manageable problems devdaily com 8 1 2 Why 00 According to the GartnerInstitute e 74 of all IT projects fail come in over budget or run past the original deadline e 28 fail altogether e 52 7 of IT projects cost 189 e Every year 75B is spent on failed IT projects 1 2 2 Symptoms of software development problems The text Rational Unified Process An Introduction 9 identifies the fol lowing symptoms that characterize failing software development projects e Inaccurate understanding of end user needs e Inability to deal with changing requirements e Modules that don t fit together e Software that s hard to maintain or extend e Late discovery of serious projects flaws e Poor software quality e Unacceptable software performance e Team members in each other s way e An untrustworthy build and release process 1 2 3 Root causes of project failure The same text identifies the root causes of these failures e Ad hoc requirements management e Ambiguous and imprecise communication e Brittle architectures e Overwhelming complexity devdaily com 9 1 2 Why 00 tions e
76. relationships and dependencies between pack ages e Package diagrams are vital for large projects State diagram e Captures the lifecycle of one or more objects Activity diagram e Advanced flowcharts e Swimlanes let you organize a set of activities according to who is per forming them devdaily com 20 1 4 UML summary O gt state 1 state 2 state 3 Figure 1 7 A state diagram captures the lifecycle of one or more objects Component diagram e The implementation view of a system e Displays the organization and dependencies between software compo nents Deployment diagram e The environment view of a system e Shows the physical relationships among software and hardware com ponents e Each node represents some computational unit usually a piece of hardware e Connections show communication paths e In practice probably not used very much though most projects have a drawing that looks something like these devdaily com 21 1 5 Object Oriented Software Development 1 5 Object Oriented Software Development e Larger processes methodologies Rational Unified Process RUP Object Oriented Software Process OOSP OPEN Process Lightweight agile processes XP Extreme Programming Cockburn s Crystal Family Open Source Highsmith s Adaptive Software Development Scrum Coad s Feature Driven Development DSDM Dyn
77. rnal changes Does any actor need to be informed about certain occurrences in the system What use cases will support and maintain the system Can all functional requirements be performed by the use cases case diagrams Use case diagrams identify use cases and actors of the system Use case actor relationships are shown with association lines Use cases appear as ovals generally in the middle of a diagram Use cases appear at various levels of detail two such levels are analysis level and design level devdaily com 37 1 7 A sample process SiteVisitor Use Cases SiteVisitor Member Figure 1 10 A sample use case diagram devdaily com 38 1 7 A sample process Use case diagrams include and extend e One use case can use or extend another use case e The secondary sub level use case is not associated directly with an actor e Stereotypes e lt lt includes gt gt use include a piece of behavior that is similar across more than one use case e lt lt extends gt gt one use case is similar to another but does more Wrapping Up Use Case Modeling Feel comfortable when you ve achieved the following goals 1 Your use cases account for all of the desired functionality of the system 2 You have clear and concise descriptions of the basic course of action with appropriate alternate courses of action 3 You have factored out common scenarios Milestone 1 Requirements Rev
78. rs devdaily com 111 3 2 IO Streams and readers byte data Reader charReader new BufferedReader new InputStreamReader new ByteArrayInputStream data UTF 8 devdaily com 112 3 3 Java networking 3 3 Java networking 3 3 1 Introduction e Socket e ServerSocket e URL e URLConnection 3 3 2 Socket e Socket socket new Socket host port e server is a String or InetAddress e UnknownHostException could not convert the given host server name to a TCP IP address e IOException could not find server or port e Methods getInetAddress getPort getLocalPort getLocalAddress getInputStream getOutputStream 3 3 3 ServerSocket e Listens for clients e Use accept O to accept incoming connections accept returns a Socket Socket socket serverSocket accept 3 3 4 ServerSocket lifecycle e A new ServerSocket is created on a port using a ServerSocket constructor e ServerSocket listens on the port using the accept method e Uses getInputStream and or getOutputStream e Server and client interact using an agreed upon communication pro tocol devdaily com 113 3 3 Java networking e Either the server or the client or both close the connection e The server goes back to listening with the accept method 3 35 URL e URL page new URL http www devdaily com e getContent e openStream e openConnect
79. rts e Describes one aspect of usage of the system without presuming any specific design or implementation e Ask what happens e Then what happens e Be relentless e All required system functionality should be described in the use cases e Actor represents a role a user can play with regard to a system e A user can serve as more than one type of actor e Use cases appear as ovals generally in the middle of a use case diagram e Analysis level and design level use cases e Should be able to write a solid paragraph or two about a design level use case e Use cases should have strong correlations with material in the user manual for the system write the manual then write the code Write the manual as though the system already exists e Use rapid prototyping as frequently as possible devdaily com 36 1 7 A sample process If you re reengineering an existing legacy system work from the user manual backward A use case captures some user visible function A use case achieves a discrete goal for the user A use case may be large or small Use cases model a dialogue between an actor and the system Questions to help identify use cases 11 What are the tasks of each actor Will any actor create store change remove or read information in the system What use case will create store change remove or read this infor mation Will any actor need to inform the system about sudden exte
80. s 2 5 1 String objects Java provides a String class to deal with sequences of characters String username Fred Flinstone The String class provides a variety of methods to operate on String objects The equals method is used to compare Strings The length method returns the number of characters in the String The operator is used for String concatenation String objects are read only also called immutable In the example below the second assignment gives a new value to the object reference str not to the contents of the string str Fred str Barney An array of char is not a String 2 5 2 StringBuffer class The StringBuffer class is often used when you need the ability to modify strings in your programs Manipulating a StringBuffer can be faster than creating re creating String objects during heavy text manipulation StringBuffer objects are mutable Useful methods include append charAt index0f insert length and replace devdaily com 70 2 5 Strings Exercise e What is the output of the following class class StringTest public static void main String args 4 String String stri str2 System System stri System System Exercise stri null str2 null Fred stri out println str1 out println str2 Barney out println str1 out println str2 str1 str2 str1 str2 e Modify the Hello application
81. s of a class devdaily com 17 1 4 UML summary sddRowToTabieModei0 void vod cresteProcessTableModel Process TableModel deleteRowFromTableModel void Figure 1 4 A class diagram showing relationships to classes in other pack ages Sequence diagram e Sequence diagrams follow the flow of entire use cases emphasis on time ordering e One sequence diagram for the basic course and alternative courses for each of your use cases Collaboration diagram e Shows how critical objects collaborate within a use case e Similar to sequence diagrams devdaily com 18 1 4 UML summary mu insert l l l getProjectiD getEntityMName getEntityType getNumRets getNumDets getComplexity getSerialField Yalue setEntityID Figure 1 5 A sequence diagram follows the flow of an entire use case devdaily com 19 1 4 UML summary BP3 new oeC ortroller OrderEntryC ontroller 1 create aCustomer Customer Figure 1 6 A collaboration diagram shows how important objects collabo rate within a use case lineltem Lineltem 4 2 create Focus on key transactions Sequence diagrams follow the flow of entire use cases emphasis on time ordering Collaboration diagrams add extra detail related to timing of mes sages Package diagram e Classes are arranged into logically ordered packages e Package diagrams show
82. s Messages are stored in queues where they can be pro cessed in the order received Publish and Subscribe Multiple subscribers are notified when messages are published JMS can guarantee message delivery Messages can be processed as part of a transaction If the transaction is rolled back the message activity is also rolled back devdaily com 137 Chapter 4 Day 4 Databases Best Practices and Final Project Getting Started Setting Up a Database Establishing a Connection Setting Up Tables Retrieving Values from Result Sets Updating Tables Milestone The Basics of JDBC Using Prepared Statements Using Joins Using Trans actions Stored Procedures SQL Statements for Creating a Stored Procedure 4 1 Databases and JDBC 4 1 1 Getting things set up What you need to get started e Java JDK and JDBC e JDBC driver for your database e A database server Oracle Informix DB2 Postgres etc e Create the database and tables you want to use 4 1 2 Connecting to the database Load the driver e Class forName jdbc DriverXYZ e Class forName org postgresql Driver 138 4 1 Databases and JDBC Create the connection e Connection conn DriverManager getConnection url loginID password e The URL jdbc postgresql database jdbc postgresql host database jdbc postgresql host port database 4 1 3 Statements e A Statement object is used to send an SQL statement to the DBMS e Cr
83. s in state Basic elements e Initial state hollow circle containing a black dot e Each additional state rectangle with rounded corners e Three standard events Entry Exit Do e Transition an arrow between two states devdaily com 45 1 7 A sample process How many state diagrams are needed e Every object has a state machine Object is created Sends messages Receives messages It is destroyed e In reality most state machines are boring so don t waste time drawing them Don t diagram an object with two states On and Off e Readability is important Activity diagrams e Remarkably similar to flowcharts e Swimlanes group a set of activities according to who is performing them e A good way to understand model business processes devdaily com 46 1 7 A sample process 1 7 6 Addressing Requirements Introduction This section shows how to trace the results of your analysis and design work back to your user requirements Objectives Upon completion of this section students will be able to e Define a requirement e Describe the nature of requirements use cases and functions What is a Requirement e A user specified criterion that the system must satisfy e Requirements define the bahvior and functionality of a proposed sys tem e Usually expressed as sentences that include the word shall or must Types of Requirements e Funct
84. so be accessed from code within the same package e A protected class member also be accessed from references of the class s type or one of it s subtypes 2 10 6 Constructors in extended classes e When you extend a class the new class must choose one of it s super class s constructors to invoke e If you do not invoke a superclass constructor as your constructors first executable statement the superclass no arg constructor is auto matically invoked before any statements in your new constructor are executed e If the superclass does not have a no arg constructor you must explic itly invoke one of the superclass s other constructors or invoke another of your own constructors using the this construct e If you use super it must be the first executable statement of the constructor e The language provides a default no arg constructor for you devdaily com 96 2 10 Extending Classes Constructor order dependencies e When an object is created all it s fields are set to default initial values e Then the constructor is invoked Constructor phases e Invoke a superclass s constructor e Initialize the fields using their initializers and any initialization blocks e Execute the body of the constructor Constructor phase example e An example of how parent child constructors work public class ParentClass public ParentClass System out println ParentClass constructor was called pub
85. so it reads the a user s name from the command line and writes the user s name as part of the output e Here is the source code for the original class public class Hello public static void main String args System out println Hello world e Assuming that the users name is Al after the changes the output of the program should be Hello Al devdaily com 71 2 6 Comments and Javadoc 2 6 Comments and Javadoc 2 6 1 Types of comments e Three different ways to put comments in your Java code define a comment to the end of the current row define a multi line comment between the two symbols 2 a Javadoc multi line comment 2 6 2 Javadoc comment tags e The following special tags in Javadoc comments have predefined pur poses see e Creates a link to other javadoc documentation e Name any identifier but qualify it sufficiently see Attr see COM missiondata web utils PageFactory param e Documents a single parameter to a method e Have one for each parameter of the method e First word is the parameter name the rest is its description param max The maximum number of words to read return e Documents the return value of a method return The number of words actually read devdaily com 72 2 6 Comments and Javadoc exception e Documents an exception thrown by the method e Should have one for each type of exception the
86. t The Rational Unified Process An Introduction 9 specifies the following purpose objectives and activities from a transition phase Purpose e Transition the software to the user community Beta testing Parallel operation with any existing legacy system Conversions of operational databases Training of users Product rollout Objectives e Achieving user self supportability e Achieving stakeholder buy in that the deployed product is complete and consistent with the evaluation criteria of the vision e Achieving final product baseline as rapidly and cost effectively as pos sible Activities e Deployment specific engineering Cutover Commercial packaging and production Sales rollout Field personnel training e Tuning activities bug fixing and enhancement for performance and usability e Assessing the deployment baseline against the vision and acceptance criteria devdaily com 30 1 7 A sample process 1 7 A sample process The next several sections provide an outline of a sample object oriented software development process Specifically this process is based on the text Use Case Driven Object Modeling with UML A Practical Approach by Rosenberg and Scott 4 This is a real process based on the theory outlined in the Rational Unified Process 1 7 1 Domain modeling First guess at domain objects What is a class e A class is a template for creating obj
87. tance variables e Access data members and methods of an instance e Discuss nested classes and Interfaces e Write your own complete Java classes 2 8 3 A Simple Class e Each object is an instance of a class e The basics of a class are it s fields and methods or attributes and behaviors class Body public long idNum public String nameFor public Body orbits devdaily com 81 2 8 Classes and objects public static long nextID 0 e First declare the name of the class Body mercury Body earth e mercury and earth are references to objects of type Body e During it s existence mercury may refer to any number of Body ob jects e Note this version of Body is poorly designed 2 8 4 Fields e A class s variables are called fields or attributes e Every Body object has its own specific instances of these fields except for nextID e Changing the orbits of one object will not affect the orbits of others 2 8 5 Access Control and Inheritance e We declared many fields of Body to be public this is not always a good design idea e Four possible access control modifiers private members declared private are accessible only in the class itself protected accessible in the class itself and are accessible to and inheritable by code in the same package and code in sub classes public accessible anywhere the class is accessible and inher ited by all subclasses
88. te the items that are un necessary redundant or irrelevant or incorrect too vague represent concepts outside the model Where else do classes come from Tangible things cars telemetry data pressure sensors Roles mother teacher politician manager Events interrupt request Interactions loan meeting intersection People humans who carry out some function Places areas set aside for people or things Things physical objects devices Organizations formally organized collections of people Concepts principles or ideas that are not tangible devdaily com 39 1 7 A sample process Build generalization relationships e Generalization one class is a refinement of another class e Define Is a relationships e Break into 1 superclass parent and 2 subclass child e Child inherits attributes and behaviors of the parent e Sometimes discover classes ahead of schedule Build associations between classes e Association A static relationship between two classes e Show dependencies between classes but not between actions e Should be a true statement about the problem space independent of time i e static e Build the list of candidate associations from the list of verbs and verb phrases and knowledge of the problem domain Examples e Order generates Trade e Portfolio places Orders e Posting involves GLAccount e Trade generates TradeLot e Some associa
89. tions are one to one some are one to many These are referred to as multiplicities e Don t worry about being more specific about numbers of one to many associations at this time e Aggregation an association in which one class is made up of other classes Has a or part of relationships devdaily com 33 1 7 A sample process Mine legacy documentation for domain classes e Relational database tables are an excellent source of domain classes e Helper classes contain attributes and operations that are relevant to more significant classes Wrapping up domain modeling Continue to iterate and refine e Draw an analysis level class diagram e The user s wants and needs are the reason your project team exists e Establish a time budget for building your initial domain model e The diagram you draw during domain modeling is just a skeleton of your object model Three key principles e Work inward from user requirements e Work outward from data requirements e Drill down from high level models to detailed design devdaily com 34 1 7 A sample process 1 7 2 Use case modeling Actors An actor is anyone or anything that must interact with the system An actor is not part of the system Actors are typically found in the problem statement and by conver sations with customers and domain experts Actors are drawn as a stick figures When dealing with actors it is important to think about roles
90. translation time If you change the included file e Works differently than lt jsp include page filename jsp gt 3 13 8 Implicit objects e Asa JSP developer certain implicit objects are made available to you e The JSP contaner provides them for you e Some objects such as request and response are passed as parameters to the servlets service method The table below provides details about each implicit object devdaily com 132 3 13 JavaServer Pages 3 13 9 Exception handling e Ifa JSP causes an exception to be thrown good practices dictate that the exception is handled by code or that the user be forwarded to an error page e Exceptions can be caught in scriptlets e Use the lt 0 page errorPage error jsp gt directive to define an error page e Identify the error page with the page directive lt page isErrorPage true i gt e The JSP container makes the implicit exception object available to a defined error page devdaily com 133 3 14 Survey of other server side Java technologies 3 14 Survey of other server side Java technologies e XML e XSLT e Enterprise Java Beans e Java Messaging Service 3 14 1 XML e eXtensible Markup Language e Derived from SGML which is also the original parent language of HTML e XML is a meta language that can be used to defined an unlimited number of custom hierarchical data formats e Example lt xml version 1 0 gt
91. ts e Show detailed interactions that occur over time among objects e Finalize the distribution of operations among classes Sequence Diagrams e Represent the major work product of our design e Draw one sequence diagram that encompasses the basic course and all alternative courses within each of your use cases One sequence diagram per use case e These results form the core of your dynamic model devdaily com 42 1 7 A sample process Four Sequence Diagram Elements e The text for the course of action of the use case e Objects e Messages e Methods operations behaviors Getting Started Four steps to creating diagrams e Copy the use case text to the left margin of the sequence diagram e Add the entity objects e Add the boundary objects e Work through the controllers one at a time Determine how to allocate behavior between the collaborating objects Putting Methods on Classes e This is the essence of interaction modeling e It s also hard e A cow needs milking Does the cow object milk itself or does the Milk object de cow itself e Convert controllers from robustness diagrams to sets of methods and messages that embody the desired behavior e An object should have a single personality Avoid schizophrenic objects e If you have objects with split personalities you should use aggregation e Use CRC cards to help e Behavior allocation is of critical importance e Don t sh
92. ts with JUnit 1 2 Build a subclass of the class TestCase Create as many test methods in this test class as necessary With JUnit if each method begins with the name test like testThis testThat etc the test methods will be discovered automatically The testing framework collects up all the tests and executes them one after another You can create a method named setUp O that sets stuff up before each test is run You can create a method named tearDown that helps you get rid of stuff after each test is run 4 2 8 A sample JUnit session Let s go back to the need for a Pizza class Here are the things we want to be able to do with our Pizza class 5 Create a means of adding toppings to a pizza Create a Pizza class and a test class for it Create methods to get the list of toppings from a pizza Create a way to remove a topping from a pizza Create a way to determine the price of a pizza For this class your first task is to make sure you can add and remove top pings How do you start devdaily com 145 4 2 JUnit 1 First make sure you have JUnit set up properly so you can easily use it 2 Next create the desired Pizza class but implement nothing 3 Next create a test class named Pizza This class will extend TestCase and will hold all of your unit tests for the Pizza class 4 In the _Pizza class start to implement the first test method The first th
93. tterhow the try clause completed normally through an exception or through a return or break finally e A mechanism for executing a section of code whether or not an excep tion is thrown Usually used to clean up internal state or to release non object re sources such as open files stored in local variables e Can also be used to cleanup for break continue and return No way to leave a try block without executing its finally clause A finally clause is always entered with a reason that reason is remem bered when the finally clause exits 2 12 7 When to use exceptions e Used for unexpected error conditions e Not meant for simple expected situations end of an input stream should be expected devdaily com 107 2 13 Packages 2 13 Packages 2 13 1 Introduction e Packages have members that are related classes interfaces and sub packages e Packages are useful for several reasons e Packages create a grouping for related interfaces and classes e Interfaces and classes in a package can use popular public names that make sense in one context but might conflict with the same name in another package e Packages can have types and members that are available only within the package 2 13 2 Package Naming e A package name should be unique A good way to ensure unique pack age names is to use an Internet domain name reversed package COM missiondata utils 2 13 3 Package Access e A p
94. tware CMM or SW CMM devdaily com 152
95. ublic class or interface is accessible to code outside that package e Types that are not public have package scope they are available to all other code in the same package but are hidden outside the package and even from code in nested packages e Package scope is the default if public protected private are not de clared 2 13 4 Package Contents e Contain functionally related classes and interfaces e Classes in a package can freely access each other s non private mem bers devdaily com 108 2 13 Packages e Should provide logical groupings for programmers looking for useful interfaces and classes e Packages can be nested inside other packages 2 13 5 Examples e The Model View Controller paradigm can help illustrate a good way of packaging MVC related classes for a fictitional Pizza Store project com com com com com com alspizzastore alspizzastore alspizzastore alspizzastore alspizzastore alspizzastore model Pizza model Topping view OrderEntryScreen view ReceiptView controller ReceiptController controller PricingController devdaily com 109 Chapter 3 Day 3 Standard Libraries amp Server side Programming 3 1 Objectives Learn how to read from and write to files with IO facilities Gain an introduction to writing network aware programs with Java Obtain a basic understanding of how to create and use threads in Java programs Learn how Remote
96. vdaily com 127 3 12 Servlets 3 12 Servlets 3 12 1 Objectives e Understand servlet framework e Write basic servlets 3 12 2 Servlet basics e Used to deliver dynamic content to web pages e Request e Response GET and POST The servlet API e Request service doGet doPost response 3 12 3 HelloWorldServlet e A sample HelloWorldServlet import java io import javax servlet import javax servlet http public class HelloWorldServlet extends HttpServlet public void doGet HttpServletRequest request HttpServletResponse response throws ServletException IOException resp setContentType text html PrintWriter out response getWriter out printin lt html gt lt body gt Hello world lt body gt lt htm1 gt out close devdaily com 128 3 12 Servlets 3 12 4 Servlet lifecycle e Handled by the servlet container e Create and initialize the servlet Handle zero or more service calls e Destroy and garbage collect the servlet A single servlet instance to handle every request 3 12 5 HTTPServlet e Override doGet to handle GET requests e Override doPost to handle POST requests e Both methods take HTTPServletRequest and HTTPServletResponse as arguments e A few other methods but used much less often doDelete doTrace doOptions doPut 3 12 6 HTTPServletRequest e getMethod e getQueryString e getRemoteHost e getRemoteAddr getAuthTyp
97. vior Commonly used between a set of classes that have a common super class The sender of a message does not have to know the type class of the recelver A single operation or attribute may be defined upon more than one class and may take on different implementations in each of those classes An attribute may point to different objects at different times devdaily com 12 1 3 Introduction to OO concepts 1 3 4 Abstraction with objects Abstraction the act of identifying software artifacts to model the problem domain Classes are abstracted from concepts This is the first step in identifying the classes that will be used in your applications Better to have too many classes than too few When in doubt make it a class 1 3 5 Message passing Objects communicate by sending messages Messages convey some form of information An object requests another object to carry out an activity by sending 1t a message Most messages pass arguments back and forth Meilir Page Jones defines three types of messages 12 1 Informative send information for the object to update itself 2 Interrogative ask an object to reveal some information about itself 3 Imperative take some action on itself or another object Grady Booch defines four types of messages 4 1 Synchronous receiving object starts only when it receives a message from a sender and it is ready 2 Balking sending object

Download Pdf Manuals

image

Related Search

Related Contents

Drucken - Firmware Center  WorldTracker RF - Tracking the World  Altec Lansing InMotion IM7  Medialon Audio Server PRO User Manual  Samsung MM-DG53 User Manual  Calofer - Soudal  Ça est un bon mot !» ou l`humour (icono  TRiロN  完成図 背もたれの調節方法 座椅子の品質表示  habitação pública no porto - Repositório Aberto da Universidade do  

Copyright © All rights reserved.
Failed to retrieve file