Using Collections and Strings in a Reusable Class - PowerPoint PPT Presentation

1 / 55
About This Presentation
Title:

Using Collections and Strings in a Reusable Class

Description:

Chapter 9: Using Collections and Strings in a Reusable Class ... expiration, provide expiration information, and activate/deactivate expiration ... – PowerPoint PPT presentation

Number of Views:35
Avg rating:3.0/5.0
Slides: 56
Provided by: steve1722
Category:

less

Transcript and Presenter's Notes

Title: Using Collections and Strings in a Reusable Class


1
Chapter 9
  • Using Collections and Strings in a Reusable
    Class

2
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

3
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 passwords functionality is encapsulated in
    the class

4
(No Transcript)
5
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

6
Design the Solution
7
(No Transcript)
8
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

9
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

10
(No Transcript)
11
  • Static variables
  • Only one copy in memory
  • Shared by all instances of the class
  • See StaticDemo.java in the Chapter 9 student
    files.

12
static variable
constructor
3 new objects
13
  • Static methods
  • Belong to the Class
  • Can be called without any instances of the class
  • See TripleThird.java and TripleThirdDemo.java in
    the Chapter 9 student files.

14
TripleThird.java
Two static methods
15
TripleThirdDemo.java
call static method
call static method
dblTriple TripleThird.TripleNumber(dblInput1)
Class name
Static method name
16
  • Create a new file in TextPad
  • Save as Password.java

17
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

18
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

19
(No Transcript)
20
Creating an ArrayList
  • An ArrayList allow resizing, insertions, and
    deletions
  • When the list size reaches capacity, the capacity
    is increased automatically
  • The ArrayList constructor can take an integer
    parameter that represents the initial capacity of
    the list
  • If the initial capacity is not given, the default
    is a size of 10

21
ArrayList class
  • Need to import java.util.ArrayList
  • Using no-arg constructor ArrayList nameList
    new ArrayList()
  • Add objects to the ArrayList nameList.add(James
    ) nameList.add(Catherine) nameList.add(Bil
    l)
  • Using size method nameList.size would contain 3

22
ArrayList class
  • ArrayList get method System.out.println(nameList
    .get(1))
  • Built-in toString method System.out.println(name
    List)would display as James, Catherine,
    Bill
  • Remove method nameList.remove(1)Bill is now
    nameList(1) James, Bill

23
ArrayList class
  • Inserting an item (adding to the original
    ArrayList) nameList.add(1, Mary)ArrayList
    now contains
  • Index 0 James
  • Index 1 Mary
  • Index 2 Catherine
  • Index 3 Bill
  • Replace an item nameList.set(1, Becky)would
    replace Mary with Becky

24
ArrayList class
  • To assign to another variable, use a
    cast String str (String)nameList.get(0)
  • Specify the type of data an ArrayList will
    hold ArrayList ltStringgt nameList new
    ArrayListltStringgt()
  • Wont need to cast when retreiving items from the
    list

25
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

26
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

27
First and second constructors
Set is a user-defined method, not written yet
28
  • Third and fourth constructors

29
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 or
    failure
  • Responsible for determining if value is valid

30
autoExpires Accessor and Mutator Methods
Local parameter variable
Class-level instance variable
31
expired Accessor and Mutator Methods
isExpired could have been named getExpired
32
expiresNotifyLimit Accessor and Mutator Methods
  • Verify that the new value for the mutator method
    is within the acceptable range

33
maxHistory Accessor and Mutator Methods
  • Pseudocode for setMaxHistory() verifies the range
    of the new value and then adjusts the history
    list accordingly

34
(No Transcript)
35
Coding Accessor Methods for Read-Only Attributes
  • Read-only attributes only require an accessor
    method, because they cannot be modified by the
    user

36
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

37
(No Transcript)
38
(No Transcript)
39
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

40
(No Transcript)
41
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

42
(No Transcript)
43
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

44
(No Transcript)
45
Coding private Helper Methods
  • Pseudocode for verifyFormat()

46
verifyFormat()
47
HashCode( )
  • Converts string values to an arbitrary integer
    value
  • See sample program TestHashCodes.java in the
    Chapter 9 student files
  • Try different values for strNum1 and strNum2
  • Note the format strNum1.hashCode()
  • Hash codes are stored as integers

48
Bitwise operators
  • Can only be used on integers and characters
  • Operates on individual bits
  • Bitwise AND
  • Bitwise OR
  • Bitwise NOT (complement operator)

49
Bitwise operators
  • num1 holds 45 00101101
  • num2 holds 14 00001110

50
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

51
Pseudocode for encrypt()
52
Encryption
  • See sample program TestEncryption.java in the
    Chapter 9 student files
  • Output in encrypt, original pswd is Hello
  • after swap, encryptPswd is lloHe
  • after reverse, encryptPswd is eHoll
  • after bitwise AND, encryptPswd is _at__at_lll
  • hashCode is 69609650
  • in Main, strNewWord is _at__at_lll69609650

53
encrypt( )
54
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

55
Chapter 9 Java Homework
  • Learn It Online1. Chapter Reinforcement
    True/False Multiple Choice, page 596
  • Only type the answers, not the questions
  • All answers must be typed and printed out
  • Debugging Assignment
  • Page 597
  • Programming Assignments
  • Pages 598 - 601
  • 2, 3, 5
  • Due 11/29/07
Write a Comment
User Comments (0)
About PowerShow.com