Chapter 9

Document Sample
Chapter 9 Powered By Docstoc
					Java Programming, 3e
              Concepts and Techniques




      Chapter 9
  Using Collections and
       Strings in a
    Reusable Class
    Objectives
    •   Develop a class for reuse
    •   Understand class and instance variables
    •   Use the final qualifier
    •   Understand the Collections Framework




Chapter 9: Using Collections and Strings in a Reusable Class   2
    Objectives
    •   Create an ArrayList object
    •   Create overloaded constructors
    •   Code accessor (get) methods
    •   Code mutator (set) methods




Chapter 9: Using Collections and Strings in a Reusable Class   3
    Objectives
    • Code accessor methods for read-only
      attributes
    • Understand when to use public and private
      methods
    • Code public instance methods
    • Use an ArrayList method



Chapter 9: Using Collections and Strings in a Reusable Class   4
    Objectives
    • Understand and use the String and
      StringBuffer classes
    • Code private helper methods
    • Test a reusable class
    • Use a JPassword field




Chapter 9: Using Collections and Strings in a Reusable Class   5
    Introduction
    • Design code with reusability in mind
    • Abstract, or separate out, the specific
      functionality of a given class
    • Design classes to provide a function
      regardless of the particular application
      where it is used
    • Use Java classes in your program when
      they can provide a needed function
Chapter 9: Using Collections and Strings in a Reusable Class   6
    Developing a Reusable Password
    Class
    • A password class is a good candidate for
      reusability
    • Passwords can have numerous characteristics
        –   Minimum length
        –   Requirement for numeric characters
        –   Expiration time
        –   Restrictions on using previously used passwords
        –   Encryption
    • The password’s functionality is encapsulated in
      the class

Chapter 9: Using Collections and Strings in a Reusable Class   7
Chapter 9: Using Collections and Strings in a Reusable Class   8
    Problem Analysis
    • Accumulate a history of recently used
      passwords
    • Verify the format of all passwords
    • Validate a given password against the current
      password value
    • Determine if the current password is
      approaching expiration, provide expiration
      information, and activate/deactivate expiration
    • Encrypt passwords using the given algorithm

Chapter 9: Using Collections and Strings in a Reusable Class   9
    Design the Solution




Chapter 9: Using Collections and Strings in a Reusable Class   10
Chapter 9: Using Collections and Strings in a Reusable Class   11
    Public and Private Methods
    • The public interface of an object contains
      methods that should be available for use by
      other programs
    • The implementation of a public method can be
      changed without changing the interface, or
      method header
    • Helper methods are used internally by the object
      and are declared private
    • Use the principle of least privilege to restrict
      access from outside the class to the minimum
      level necessary
Chapter 9: Using Collections and Strings in a Reusable Class   12
    Understanding Class and
    Instance Variables
    • Class variables are shared by all objects of a
      class
        – One value regardless of the object using it
        – Designated by the keyword, static
    • Instance variables exist only when an object
      exists
        – Values are not shared among object instances
    • Class and instance variables have class scope
    • Local variables are defined in a method and are
      in scope only within that method

Chapter 9: Using Collections and Strings in a Reusable Class   13
Chapter 9: Using Collections and Strings in a Reusable Class   14
Chapter 9: Using Collections and Strings in a Reusable Class   15
    Using the Final Qualifier
    • Final variables allow constants to have a name
        – Avoids duplicate literals in a program
    • By convention, finals use all capital letters
    • Blank finals can be left uninitialized when
      defined
        – Constructors may supply different values
        – Are not often used due to potentially different values
    • Final variables should be declared static to
      ensure the same value is used for all instances

Chapter 9: Using Collections and Strings in a Reusable Class       16
    Understanding the Collections
    Framework
    • A number of commonly used data structures in
      the Java API
    • Interfaces
        – Provide a general structure independent of the
          representation
    • Implementations
        – Provide reusable data structures from interfaces
        – For example, an ArrayList implements the list
          interface an an array
    • Algorithms
        – Provide the means of performing common operations
Chapter 9: Using Collections and Strings in a Reusable Class   17
Chapter 9: Using Collections and Strings in a Reusable Class   18
Chapter 9: Using Collections and Strings in a Reusable Class   19
    Creating an ArrayList
    • An ArrayList allow resizing, insertions, and
      deletions
    • The capacity of an ArrayList is at least as large
      as the size of the array
    • When the list size reaches capacity, the capacity
      is increased automatically
    • ArrayList yields faster access than LinkedList
    • The ArrayList constructor takes an integer
      parameter that represents the initial capacity of
      the list

Chapter 9: Using Collections and Strings in a Reusable Class   20
    Creating Overloaded
    Constructors
    • A constructor has no return data type
    • A default constructor has no parameters
        – If there are no coded constructors, the compiler
          creates a default constructor
    • If a constructor has no arguments, the instance
      variables of the class are given default values
    • Java allows multiple constructor methods
        – Multiple methods with the same name are said to be
          overloaded
        – Overloaded methods must have unique method
          signatures
Chapter 9: Using Collections and Strings in a Reusable Class   21
    Creating Overloaded
    Constructors
    • A combination of the method name and the
      formal parameter list in the method header
    • The parameter list must be unique for
      overloaded methods
        – Different number of parameters
        – Same number of parameters with a different ordering
          of data types
    • The return data type is not used in determining
      the method signature

Chapter 9: Using Collections and Strings in a Reusable Class   22
Chapter 9: Using Collections and Strings in a Reusable Class   23
    Coding Accessor (Get) and
    Mutator (Set) Methods
    • User programs access private instance variables of a
      class by using instance methods
    • Accessor methods provide the value of a private variable
        – Usually named with the verb, get, followed by the instance
          variable name
        – Sometimes named with the verb, is, for boolean variables
    • Mutator methods accept a proposed value for the
      variable
        – Usually named with the verb, set, followed by the variable name
        – Return type can be boolean to indicate success of failure
        – Responsible for determining if value is valid


Chapter 9: Using Collections and Strings in a Reusable Class           24
    autoExpires Accessor and
    Mutator Methods




Chapter 9: Using Collections and Strings in a Reusable Class   25
    expired Accessor and Mutator
    Methods




Chapter 9: Using Collections and Strings in a Reusable Class   26
    expiresNotifyLimit Accessor and
    Mutator Methods
    • Verify that the new value for the mutator method is within
      the acceptable range




Chapter 9: Using Collections and Strings in a Reusable Class   27
    maxHistory Accessor and
    Mutator Methods
    • Pseudocode for setMaxHistory() verifies the range of the
      new value and then adjusts the history list accordingly




Chapter 9: Using Collections and Strings in a Reusable Class   28
Chapter 9: Using Collections and Strings in a Reusable Class   29
    Coding Accessor Methods for
    Read-Only Attributes
    • Read-only attributes only require an accessor method,
      because they cannot be modified by the user




Chapter 9: Using Collections and Strings in a Reusable Class   30
    Coding public Instance Methods
    • set()
        – Trims extra space from a new password
        – Verifies format and encrypts
        – Checks password history list and adds the new
          password, if not already present
        – Sets expiration
    • validate()
        – Verifies the entered password is the latest entry in list
          and decrements remaining uses, if necessary
    • Both methods throw exceptions for invalid or
      expired passwords
Chapter 9: Using Collections and Strings in a Reusable Class     31
Chapter 9: Using Collections and Strings in a Reusable Class   32
Chapter 9: Using Collections and Strings in a Reusable Class   33
    Using ArrayList Methods
    • All objects in Java inherit Object as the root
      class
    • Any object may be referenced as an Object
    • ArrayList can maintain a list of any type of object
      by using Object as the parameter or return type
    • Downcasting must be used when retrieving data
      from ArrayList
        – Use the cast operator with the specific class type
        – If necessary, use the instanceof operator to verify the
          object type before downcasting

Chapter 9: Using Collections and Strings in a Reusable Class    34
Chapter 9: Using Collections and Strings in a Reusable Class   35
    Using the String Class
    • The String class supports immutable string
      values
        – String objects are constants
    • String literals are implemented as instances of
      the String class
    • If you assign a new value to a String, a new
      String is created with that value
        – The JVM garbage collector disposes of the old value
    • String concatenation is implemented with the
      StringBuffer class

Chapter 9: Using Collections and Strings in a Reusable Class   36
Chapter 9: Using Collections and Strings in a Reusable Class   37
    Using the StringBuffer Class
    • The StringBuffer class implements a mutable
      sequence of characters
    • The length and content may be modified at any
      time
    • If the capacity of the internal buffer is exceeded,
      it is expanded automatically
    • A StringBuffer may be created with no
      arguments, a String literal, a String variable, or a
      concatenation of multiple strings

Chapter 9: Using Collections and Strings in a Reusable Class   38
Chapter 9: Using Collections and Strings in a Reusable Class   39
    Coding private Helper Methods
    • Pseudocode for verifyFormat()




Chapter 9: Using Collections and Strings in a Reusable Class   40
    verifyFormat()




Chapter 9: Using Collections and Strings in a Reusable Class   41
    The encrypt() Method
    • Encrypted data is called ciphertext
    • Encryption techniques
        – Substitution and rotation of letters
             • Use substring() and reverse() methods
        – Bit manipulation
             • Use the bitwise AND operator to compare the bits in each
               character of the encrypted and original password
        – Hash codes
             • Use hashcode() to transform a string into a shorter, fixed-
               length value
             • Hash codes are not necessarily unique

Chapter 9: Using Collections and Strings in a Reusable Class                 42
    Pseudocode for encrypt()




Chapter 9: Using Collections and Strings in a Reusable Class   43
    encrypt()




Chapter 9: Using Collections and Strings in a Reusable Class   44
    Testing a Reusable Class
    • The PasswordDemo test program provides a GUI
    • The JPassword field provides masking of an entered
      password with alternate characters for security
        – An asterisk is the default
    • Exceptions from the Password class are caught and a
      message box displays the passed String message
    • Test the Password class
        – Enter new and current passwords
        – Change the password
        – Test valid and invalid inputs



Chapter 9: Using Collections and Strings in a Reusable Class   45
    Summary
    •   Develop a class for reuse
    •   Understand class and instance variables
    •   Use the final qualifier
    •   Understand the Collections Framework




Chapter 9: Using Collections and Strings in a Reusable Class   46
    Summary
    •   Create an ArrayList object
    •   Create overloaded constructors
    •   Code accessor (get) methods
    •   Code mutator (set) methods




Chapter 9: Using Collections and Strings in a Reusable Class   47
    Summary
    • Code accessor methods for read-only
      attributes
    • Understand when to use public and private
      methods
    • Code public instance methods
    • Use an ArrayList method



Chapter 9: Using Collections and Strings in a Reusable Class   48
    Summary
    • Understand and use the String and
      StringBuffer classes
    • Code private helper methods
    • Test a reusable class
    • Use a JPassword field




Chapter 9: Using Collections and Strings in a Reusable Class   49
Java Programming, 3e
              Concepts and Techniques




Chapter 9 Complete
 Using Collections and
      Strings in a
   Reusable Class

				
DOCUMENT INFO