Docstoc

Microsoft PowerPoint - Chapter 7

Document Sample
Microsoft PowerPoint - Chapter 7 Powered By Docstoc
					                                                                                                            Chapter Objectives
                                                                                                                                                 After studying this chapter, you should be able to:
Java:                                                                                                                                             • Write queries to reflect the state of an object
                                                                                                                                                  • Use queries to write a test harness that tests your class
                                                                                                                                                  • Write classes that use types other than integer, including floating-
Learning to Program with Robots                                                                                                                     point types, booleans, characters, and strings
                                                                                                                                                  • Write and use an enumerated type
                                                                                                                                                  • Write a class modeling a simple problem
                                                                                                                                                  • Describe the difference between a class variable and an instance
                                                                                                                                                    variable
Chapter 07: More on Variables and Methods                                                                                                         • Write classes that implement an interface and can be used with
                                                                                                                                                    provided graphical user interfaces from the becker library




                                                                                                                                                 Java: Learning to Program with Robots                                    2




                                                                                                                                                 import becker.util.Test;
7.1.1: Testing a Command (1/3)




                                                                                                            7.1.1: Testing a Command (2/3)
                                 Testing a class involves conducting many individual tests.
                                 Collectively, these tests are called a test suite.                                                              public class TestHarness
                                                                                                                                                 {
                                 Each test involves five steps:                                                                                    public static void main(String[ ] args)
                                    1. Decide which method you want to test.                                                                       { // Step 1: Test move method
                                                                                                                                                         // Step 2: Put robot in an empty city on (4,2) facing East.
                                    2. Set up a known situation.                                                                                         SimpleCity c = new SimpleCity();
                                                                                                                                                         SimpleBot karel = new SimpleBot(c, 4, 2, Constants.EAST);
                                    3. Determine the expected result of executing the method.
                                                                                                                                                         // Step 3: The robot should end up on (4,3) facing East.
                                    4. Execute the method.                                                                                               // Step 4: Execute the method.
                                    5. Verify the results.                                                                                               karel.move();
                                                                                                                                                         // Step 5: Verify the result.
                                                                                                                                                         Test tester = new Test();
                                 Ideally, we would like to test the class after each change. This implies                                                tester.ckEquals("new ave", 3, karel.getAvenue());
                                 automating the testing.                                                                                                 tester.ckEquals("same str", 4, karel.getStreet());
                                                                                                                                                         tester.ckEquals("same dir", Constants.EAST, karel.getDirection());
                                                                                                                                                     }
                                                                                                                                                 }




                                 Java: Learning to Program with Robots                                 3                                         Java: Learning to Program with Robots                                    4
                                                                                                            7.1.3: Using Multiple Main Methods
7.1.1: Testing a Command (3/3)




                                 How does ckEquals work?                                                                                         Each class may have its own main method. This allows us to put a test
                                                                                                                                                 harness into every class! Write one more main method in its own class
                                 public class Test                                                                                               (as we have been doing) to run the program.
                                 {
                                   public void ckEquals(String msg, int expected, int actual)                                                    public class SimpleBot extends Paintable
                                   {                                                                                                             { private int street;
                                     if (expected == actual)                                                                                       private int avenue;
                                     { print passed message                                                                                        …
                                     } else                                                                                                        public SimpleBot(…)     { … }
                                                                                                                                                   public void move()         { … }
                                     { print failed message
                                     }                                                                                                               public static void main(String[ ] args)
                                   }                                                                                                                 { SimpleCity c = new SimpleCity();
                                 }                                                                                                                     SimpleBot karel = new SimpleBot(c, 4, 2, Constants.EAST);

                                                                                                                                                         karel.move();

                                                                                                                                                         Test tester = new Test();
                                                                                                                                                         tester.ckEquals("new ave", 3, karel.getAvenue());
                                                                                                                                                         tester.ckEquals("same str", 4, karel.street);
                                                                                                                                                         …
                                                                                                                                                     }
                                                                                                                                                 }
                                 Java: Learning to Program with Robots                                 5                                         Java: Learning to Program with Robots                                    6
7.2: Using Numeric Types (1/3)




                                                                                                                                    7.2 Using Numeric Types (2/3)
                                 What is a type?                                                                                                                              Java has six numeric types.
                                     • It is used when declaring a {instance, temporary, parameter}                                                                           Integer Types
                                       variable. For example:                                                                                                                                                                                             Precision
                                       private int street;                                                   // instance variable                                             Type                           Smallest Value               Largest Value
                                       Robot karel = new Robot(…);                             // temporary variable
                                                                                                                                                                              byte                                      -128                         127 exact
                                                                                                                                                                              short                                   -32,768                     32,767 exact
                                     • The type specifies the values the variable may take on.
                                                                                                                                                                              int                    -2,147,483,648            2,147,483,647 exact
                                          • street may be assigned integers like -10, 0, and 49 (and only
                                                                                                                                                                              long                                - 9,223,372,036,854,775,807 exact
                                            integers).
                                                                                                                                                                                          9,223,372,036,854,775,808
                                          • karel may be assigned Robot objects.

                                                                                                                                                                              Floating-Point Types
                                     • The type specifies the operations that may be performed.                                                                               Type         Smallest Magnitude                         Largest Magnitude Precision
                                          • street may be used with +, -, *, /, =, ==, etc.                                                                                   float                  ±1.40239846 x 10-45             ±3.40282347 x 1038 about 7
                                          • karel may be used with the method invocation operator, . (dot):                                                                                                                                             digits
                                            karel.move(), etc.                                                                                                                double ±4.940656458412 x 10-324 ±1.7976931348623 x 10308 about 16
                                                                                                                                                                                                                                                          digits
                                 Java: Learning to Program with Robots                                                       7                                                Java: Learning to Program with Robots                                                 8




                                                                                                                                    7.2.3: Converting Between Numeric Types
7.2: Using Numeric Types (3/3)




                                 Operations available on numeric types:
                                                                                                                                                                               int i = 159;
                                                                                                                                                                               double d = i;
                                                                                                                                                                                                                      The integer 159 is implicitly converted to
                                 * / %                                                                                                                                                                                159.0 before assignment to d.
                                                                         multiplication, division, remainder
                                 + -                                     addition, subtraction                                                                                 double d = 3.999;
                                                                                                                                                                               int i = d;
                                                                                                                                                                                                                      This results in a compile-time error. Java
                                 < <= > >= != ==                         comparison                                                                                                                                   doesn’t know what to do with the .999,
                                 =                                       assignment                                                                                                                                   which can’t be stored in an int.
                                                                                                                                                                               double d = 3.999;
                                                                                                                                                                               int i = (int)d;
                                                                                                                                                                                                                      Java converts the double value to an integer
                                 The type of *, /, %, +, and – is the same as the largest of the operands.                                                                                                            by dropping the decimal part (not rounding).
                                                                                                                                                                               or                                     That is, i becomes 3.
                                                                                                                                                                               int j = (int)(d * d / 2.5);
                                 For example:
                                       int a = 2;
                                       double b = 1.5;
                                 The result of a + b is 3.5 because b, a double, stores larger numbers
                                 than a, an int.


                                 Java: Learning to Program with Robots                                                       9                                                Java: Learning to Program with Robots                                                10




                                 double carPrice = 12225.00;
                                                                                                                                    7.3.1: The Boolean Type
7.2.4: Formatting Numbers




                                 double taxRate = 0.15;
                                                                                                                                                                              A boolean variable stores either true or false.

                                 System.out.println("Car: " + carPrice);                                                                                                      public class SimpleBot extends Paintable
                                 System.out.println("Tax: " + carPrice * taxRate);                                                                                            { private int street;
                                 System.out.println("Total: " + carPrice * (1.0 + taxRate));                                                                                    private int avenue;                                       Instance variables,
                                                                                                                                                                                private boolean isBroken = false;
                                                                                                                                                                                …
                                                                                                                                                                                                                                          temporary variables,
                                 This code gives the following output:                                                                                                                                                                    parameter variables, and
                                                                                                                                                                                  public void breakRobot()                                constants can all be of
                                                                                                                                                                                  { this.isBroken = false;                                type boolean.
                                 Car: 12225.0
                                                                                                                                                                                  }
                                 Tax: 1833.75
                                 Total: 14058.749999999998
                                                                                                                                                                                  public void move()
                                 We would like to format it using a familiar currency symbol, such as $,                                                                          { // Ignore a command to move if the robot is broken.
                                 and two decimal places.                                                                                                                            if (!this.isBroken)
                                 import java.text.NumberFormat;                                                                                                                     { this.street += this.strOffset();
                                 …                                                                                                                                                      this.avenue += this.aveOffset();
                                 NumberFormat money = NumberFormat.getCurrencyInstance();                                                                                               Utilities.sleep(400);
                                 …                                                                                                                                                  }
                                 System.out.println(Total: " + money.format(carPrice * (1.0 + taxRate)));                                                                         }
                                                                                                                                                                                  …
                                                                                                                                                                              }
                                 Java: Learning to Program with Robots                                                      11                                                Java: Learning to Program with Robots                                                12
7.3.2: The Character Type (2/2)




                                                                                                                                    7.3.3: Using Strings
                                     Some special characters are written with escape sequences:                                                                      A string is a sequence of characters. They are used frequently in Java
                                     Sequence Meaning                                                                                                                programs.
                                     \'                  Single quote
                                                                                                                                                                     public class StringExample
                                     \"                  Double quote                                                                                                {
                                     \\                                                                                                                              public static void main(String[ ] args)
                                                         Backslash                                                                                                   { String msg = "Don't drink and drive.";
                                     \n                  Newline – used to start a new line of text when printing at
                                                         the console.                                                                                                    System.out.println("Good advice: " + msg);
                                                                                                                                                                     }
                                     \t                  Tab – inserts space so the next character is placed at the                                                  }
                                                         next tab stop.
                                     \b                  Backspace – moves the cursor backwards over the                                                             String is a class (like Robot), but has special support in Java:
                                                         previously printed character.                                                                                   • Java will automatically construct a String object for a sequence of
                                     \r                  Return – moves the cursor to the beginning of the current                                                         characters between double quotes.
                                                         line.                                                                                                           • Java will “add” two strings together with the plus operator to create
                                     \f                  Form feed – moves the cursor to the top of the next page of                                                       a new string. This is called concatenation.
                                                         a printer.                                                                                                      • Java will automatically convert primitive values and objects to
                                     \udddd              A Unicode character, each d being a hexadecimal digit.                                                            strings before concatenating them with a string.
                                     Java: Learning to Program with Robots                                                    13                                     Java: Learning to Program with Robots                                                     14




                                     import becker.robots.*;
7.3.3: Special Support for Strings




                                                                                                                                    7.3.3: Overriding toString
                                     public class Main              A String object is created automatically.                                                        To convert an object to a String, Java calls the object’s toString
                                     {                                                                                                                               method. Classes should override toString to return a meaningful value.
                                       public static void main(String[ ] args)
                                       { String greeting = "Hello";                                                                                                  public class SimpleBot extends Paintable
                                         String name = "karel";                   Four concatenated strings.                                                         { private int street;
                                                                                                                                                                       private int avenue;
                                             System.out.println(greeting + ", " + name + "!");                                                                         private int direction;
                                                                                                                                                                       …
                                         Primitive automatically converted to string.
                                             System.out.println("Did you know that 2*PI = " + 2*Math.PI + "?");                                                          /** Represent a SimpleBot as a string. */
                                                                                                                                                                         public String toString()
                                             City c = new City();                                                                                                        { return "SimpleBot" +
                                             Robot karel = new Robot(c, 1, 2, Direction.SOUTH);                                                                            "[street=" + this.street +
                                             System.out.println("c=" + c);                                                                                                 ", avenue=" + this.avenue +
                                       }                                           Object automatically                                                                    ", direction=" + this.direction +
                                     }                                                                                                                                     "]";
                                                                                   converted to string.
                                     Hello, karel!                                                                                                                       }
                                     Did you know that 2*PI = 6.283185307179586?                                                                                     }
                                     c=becker.robots.City[SimBag[robots=[becker.robots.Robot[street=1, av
                                     enue=2, direction=SOUTH, isBroken=false,numThingsInBackpack=0]], t
                                     hings=[ ]]]

                                     Java: Learning to Program with Robots                                                    15                                     Java: Learning to Program with Robots                                                     16




                                     public class StringQueryDemo
                                                                                                                                    7.3.3: Querying a String (2/3)
7.3.3: Querying a String (1/3)




                                     {
                                                                                                                                                                     Method                                  Description
                                       public static void main(String[ ] args)                                                                                       int length()                            How many characters are in this string?
                                       { String s1 = "A string to play with.";
                                         String s2 = "Another string.";                                                                                              char charAt(                            Which character is at the given index
                                                                                                                                                                         int index)                          (position)? Indices start at 0.
                                             int s1Len = s1.length();
                                             System.out.println("'" + s1 + "' is " + s1Len + " characters long.");
                                                                                                                                                                     int compareTo(                          Return 0 if this string is equal to aString; a
                                                                                                                                                                         String aString)                     negative integer if this string is lexicograph-
                                             if (s1.compareTo(s2) < 0)                                                                                                                                       ically smaller than aString, and a positive
                                             { System.out.println("'" + s1 + "' appears before '" + s2 + "' in the dictionary.");                                                                            integer if this string is larger than aString.
                                             } else if (s1.compareTo(s2) > 0)
                                             { System.out.println("'" + s1 + "' appears after '" + s2 + "' in the dictionary.");                                     boolean equals(                         Return true if this string is the same as anObj.
                                             } else                                                                                                                      Object anObj)
                                             { System.out.println("The two strings are equal.");
                                             }                                                                                                                       boolean startsWith( Return true if this string starts with the prefix.
                                                                                                                                                                      String prefix)
                                             int pos = s1.indexOf("play");
                                             System.out.println("'play' appears at position " + pos);

                                             System.out.println("The character at index 3 of '" + s2 + "' is " + s2.charAt(3));
                                         }
                                     }
                                     Java: Learning to Program with Robots                                                    17                                     Java: Learning to Program with Robots                                                     18
                                                                                                                                                                                public class StringTransformDemo
7.3.3: Querying a String (3/3)




                                                                                                                                      7.3.3: Transforming a String (1/2)
                                          Method                                  Description                                                                                   {
                                          int indexOf(                            Returns the index within this string of the first                                               public static void main(String[ ] args)
                                                                                  instance of ch. Returns -1 if it does not occur.                                                {
                                              char ch)
                                                                                                                                                                                  String w = "warning: ";
                                          int indexOf(char ch, Returns the index within this string of the first                                                                  String x = w.toUpperCase();
                                            int fromIndex)     instance of ch that occurs at or after                                                                             String y = w.trim().toUpperCase();
                                                                                                                                                                                  String z = w.substring(1, 4);
                                                               fromIndex. Returns -1 if it does not occur.
                                          int indexOf(                            Returns the index of the first character of the                                                   System.out.println(w + "Core breach imminent!");
                                            String subString)                     first occurrence of subString; -1 if it does not                                                  System.out.println(x + "Core breach imminent!");
                                                                                  occur within this string.                                                                         System.out.println(y + "Core breach imminent!");

                                          int lastIndexOf(                        Returns the index of the last occurrence of the                                                   System.out.println(z);
                                            char ch)                              given character within this string. Returns -1                                                    }
                                                                                  if the character does not occur.                                                              }
                                                                                                                                                                                Output:
                                                                                                                                                                                warning: Core breach imminent!
                                                                                                                                                                                WARNING: Core breach imminent!
                                                                                                                                                                                WARNING:Core breach imminent!
                                                                                                                                                                                arn
                                          Java: Learning to Program with Robots                                                  19                                             Java: Learning to Program with Robots                                                  20
7.3.3: Transforming a String (2/2)




                                                                                                                                      7.3.4: Understanding Enumerations (1/2)
                                          Method                                                Description                                                                     Programmers often need to deal with sets of values:
                                          String replace(char oldChar,                          Returns a copy of this string with                                                 Gender: male, female
                                            char newChar)                                       all occurrences of oldChar                                                         Direction: north, south, east, west
                                                                                                replaced with newChar.
                                                                                                                                                                                   Grade of gasoline: bronze, silver, gold
                                          String substring(int beginIndex, Returns a new string containing
                                            int endIndex)                  all the characters between
                                                                           beginIndex and endIndex-1,                                                                           What can go wrong with code like the following?
                                                                                                inclusive.                                                                            public static final int EAST = 0;
                                                                                                                                                                                      public static final int SOUTH = 1;
                                          String toUpperCase()                                  Returns a copy of this string that                                                    public static final int WEST = 2;
                                                                                                has all the lowercase characters                                                      public static final int NORTH = 3;
                                                                                                replaced with uppercase
                                                                                                                                                                                      public void face(int directionToFace)
                                                                                                equivalents.                                                                          { …
                                          String toLowerCase()                                  Returns a copy of this string that
                                                                                                has all the uppercase characters
                                                                                                replaced with lowercase
                                                                                                equivalents.


                                          Java: Learning to Program with Robots                                                  21                                             Java: Learning to Program with Robots                                                  22
                                                                                                                                      7.5.1: Using Class Variables (1/2)
7.3.4: Understanding Enumerations (2/2)




                                          A better solution…                                                                                                                    Instance variables store a value on a                           SavingsAccount
                                                                                                             Enumerations are like                                              per-object basis. Every object has its                  -double balance
                                          /** An enumeration of the four compass directions.
                                                                                                             classes:                                                           own copy of the variable that may be                    -String ownerName
                                          *
                                          * @author Byron Weber Becker */
                                                                                                             • Documented the                                                   different from the value stored by other                -double interestRate
                                                                                                               same way.                                                        objects.                                                +Account(String theOwnersName)
                                          public enum Direction
                                                                                                                                                                                                                                        +void deposit(double amount)
                                          {                                                                  • Go into their own                                                                                                        +void withdraw(double amount)
                                            EAST, SOUTH, WEST, NORTH                                                                                                                                                                    +double getBalance( )
                                          }                                                                    file.
                                                                                                                                                                                                                                        +void payInterest( )
                                                                                                             Values are placed in a                                                                                                     +void setInterestRate(double rate)
                                          public class SimpleBot extends Paintable                           comma-separated list.                                                                                                      +double getInterestRate( )
                                          {
                                            private int street;                                                                                                                 public class SavingsAccount extends Object
                                            private int avenue;                                                                                                                 { private double balance = 0.0;
                                            private Direction dir;                                                                                                                private String ownerName;             Every savings account has
                                            …                                                                                                                                     private double interestRate = 0.025;  its own balance and owner.
                                              public void face(Direction directionToFace)                                                                                           public void setInterestRate(double rate)
                                              { while (this.dir != directionToFace)                                                                                                 { this.interestRate = rate;              All savings accounts             should
                                                { this.turnLeft();                                                                                                                  }
                                                                                                                                                                                                                                        have the same interest rate –
                                                }                                                                                                                               }                              Sets the interest rate
                                              }                                                                                                                                                                                         but an instance variable
                                                                                                                                                                                                               for only this account.   allows them to be different.
                                          }
                                          Java: Learning to Program with Robots                                                  23                                             Java: Learning to Program with Robots                                                  24
                                     public class SavingsAccount extends Object                                                                                            public class SavingsAccount extends Object




                                                                                                                                      7.5.1: Assigning Unique ID Numbers
7.5.1: Using Class Variables (2/2)



                                     { private double balance = 0.0;                                                                                                       { private double balance = 0.0;
                                                                                                       Class variables
                                       private String ownerName;                                                                                                             private String ownerName;
                                       private static double interestRate = 0.025;                     (also known as                                                        private static double interestRate = 0.025;
                                                                                                       static variables) are                                                 private final int accountNum;
                                         public double getInterestRate()                               shared by all of the                                                  private static int nextAccountNum = 0;
                                         { // The preferred way to reference a class variable.         instances of a class.
                                           return SavingsAccount.interestRate;                                                                                                 public SavingsAccount(String owner)
                                         }                                                                                                                                     { super();
                                                                                                         SavingsAccount
                                         public double getInterestRate()                                                                                                         this.ownerName = owner;
                                         { // Another way to reference a class variable.         -double balance                                                                 this.accountNum = nextAccountNum;
                                           return this.interestRate;                             -String ownerName                                                               SavingsAccount.nextAccountNum += 1;
                                                                                                 -static double interestRate
                                         }                                                                                                                                     }
                                                                                                 +Account(String theOwnersName)
                                         public double getInterestRate()
                                                                                                 +void deposit(double amount)
                                         { // Still another way to reference a class variable.   +void withdraw(double amount)                                                 public double getInterestRate()
                                           return interestRate;                                  +double getBalance( )                                                         { // The preferred way to reference a class variable.
                                         }                                                       +void payInterest( )                                                            return SavingsAccount.interestRate;
                                                                                                 +void setInterestRate(double rate)                                            }
                                         public void setInterestRate(double rate)                +double getInterestRate( )
                                         { SavingsAccount.interestRate = rate;                                                                                                 public void setInterestRate(double rate)
                                         }                                                                                                                                     { SavingsAccount.interestRate = rate;
                                     }                                                                  Sets the interest rate                                                 }
                                                                                                        for all accounts.                                                  }
                                     Java: Learning to Program with Robots                                                      25                                         Java: Learning to Program with Robots                                               26




                                     public class SavingsAccount extends Object


                                                                                                                                      7.5.2: Using Class Methods (2/2)
7.5.2: Using Class Methods (1/2)




                                     { …
                                                                                                                                                                           Helpful class methods in the Java library include:
                                       private static double interestRate = 0.025;                                                                                         In the Math class:
                                                                                                                                                                           int abs(int x)                                     double pow(double x, double y)
                                         public static double getInterestRate()                                                                                            double abs(double x)                               double random()
                                         { return SavingsAccount.interestRate;                                                                                             double cos(double x)                               long round(double x)
                                         }                                                                                                                                 double log(double x)                               double sin(double x)
                                                                                                                                                                           int max(int x, int y)                              double sqrt(double x)
                                         public static void setInterestRate(double rate)
                                                                                                                                                                           double max(double x, double y)                     double tan(double x)
                                         { SavingsAccount.interestRate = rate;
                                                                                                                                                                           int min(int x, int y)                              double toDegrees(double x)
                                         }
                                                                                                                                                                           double min(double x, double y)                     double toRadians(double x)
                                         public static void main(String[ ] args)                                                                                           In the Character class:
                                         { Test.ckEquals("initial rate", 0.025, SavingsAccount.getInterestRate());                                                         boolean isDigit(char ch)                           boolean isUpperCase(char ch)
                                           SavingsAccount bill = new SavingsAccount("Bill Gates");                                                                         boolean isLetter(char ch)                          boolean isWhitespace(char ch)
                                           SavingsAccount melinda = new SavingsAccount("Melinda Gates");                                                                   boolean isLowerCase(char ch)
                                           Test.ckEquals("initial rate", 0.025, bill.getInterestRate());
                                                                                                                                                                           Usage:
                                             SavingsAccount.setInterestRate(0.030);                                                                                        if (Math.random() < 0.50)
                                             Test.ckEquals("new rate", 0.030, SavingsAccount.getInterestRate());                                                           { // do something about ½ of the time
                                             Test.ckEquals("new rate", 0.030, bill.getInterestRate());                                                                     } else
                                             Test.ckEquals("new rate", 0.030, melinda.getInterestRate());                                                                  { // do something else about ½ of the time
                                         }                                                                                                                                 }
                                     }
                                     Java: Learning to Program with Robots                                                      27                                         Java: Learning to Program with Robots                                               28
7.7.2: The toString Pattern




                                                                                                                                      7.7.3: The Enumeration Pattern




                                     Name: toString                                                                                                                        Name: Enumeration
                                     Context: You want to easily print information about an object, often                                                                  Context: You would like variables to hold a value from a specific set
                                     for debugging.                                                                                                                        of values such as MALE or FEMALE or one of the four directions.
                                     Solution: Override the toString method in each class to print out                                                                     Solution: Define an enumeration type listing the desired values.
                                     relevant information.                                                                                                                     public enum «typeName»
                                         public String toString()                                                                                                              { «valueName1», «valueName2», «valueName3», …, «valueNameN»
                                         { return "«className»[" +                                                                                                             }
                                                   "«instanceVarName1»=" + this.«instanceVarName1» +                                                                       For example:
                                                   ", «instanceVarName2»=" + this.«instanceVarName2» +                                                                         public enum JeanStyle
                                                   ...                                                                                                                         { CLASSIC, RELAXED, BOOT_CUT, LOW_RISE, STRAIGHT
                                                   ", «instanceVarNameN»=" + this.«instanceVarNameN» +                                                                         }
                                                   "]";
                                         }                                                                                                                                     pbulic class DenimJeans
                                     Consequences: This method is called automatically by print and                                                                            { private JeanStyle style;
                                                                                                                                                                                 public DenimJeans(JeanStyle aStyle)…
                                     println, making it easy to print relevant information.
                                                                                                                                                                           Consequences: Enumeration variables may have only values defined
                                     Related Patterns: This is a specialization of the Query pattern.
                                                                                                                                                                           in the enumeration, helping to avoid programming errors.
                                                                                                                                                                           Related Patterns: Named Constant

                                     Java: Learning to Program with Robots                                                      29                                         Java: Learning to Program with Robots                                               30
7.7.4: The Assign a Unique ID Pattern




                                                                                                                     7.8: Concept Map
                                        Name: Assign a Unique ID                                                                          testing                                                              starts w ith                                  a known
                                                                                                                                                                                                                                                             situatio n
                                        Context: Each instance of a class requires a unique identifier.                                                                                                                                                                                    integer
                                                                                                                                                                                                                                                                                            types
                                                                                                                                                                                                                                                             incl ude




                                                                                                                                          ve rif h a vio r
                                        Solution: Store the unique ID in an instance variable. Use a class




                                                                                                                                           ve rif ies co
                                                                                                                                              be
                                                                                                                                                                                                      types




                                                                                                                                                ies c o f
                                        variable to maintain the next ID to assign.                                                                                                                                               numeric                                   floating
                                                                                                                                                                                                                                                         include           point types




                                                                                                                                                      o rr e




                                                                                                                                                                                                                 in c
                                           public class «className»…                                                                                                                          rn                                   types
                                                                                                                                                                                          e tu




                                                                                                                                                                                                                     lud
                                                                                                                                                           rre ct valu
                                                                                                                                                                                        er




                                                                                                                                                            ct




                                                                                                                                                                                                                      e
                                           { private int «uniqueID»;                                                                                                                  av                                                                                                           Strings
                                                                                                                                                                                  h
                                             private static int «nextUniqueID» = «firstID»;




                                                                                                                                                                       es in
                                                                                                                                                                      methods                                                                                                                      char




                                                                                                                                                                                            ve
                                                                                                                                                                                          ha
                                               public «className»(…)                                                                                                                                                       enumerations




                                                                                                                                                                                                               de
                                                                                                                                                                                                                                                                                               b oolean
                                               { …                                                                                                                                                                                                             interfaces




                                                                                                                                                                                                                 fin
                                                                                                                                                    variables                                                                            expli




                                                                                                                                                                                                                     e
                                                                                                                                                                                                                                             c itly




                                                                                                                                                                                                                    va
                                                 this.«uniqueID» = «className».«nextUniqueID»;                                                                                                                                             valid list




                                                                                                                                                                                                                      lid
                                                                                                                                                                                                                                                                                list
                                                 «className».«nextUniqueID» += 1;                                                                                                                              h old                                                                   req
                                                                                                                                                                                                                   can b e                          values                                uir
                                               }                                                                                                                                                                                                                                              ed
                                                                                                                                                                                         objects




                                                                                                                                                                           ca
                                           }




                                                                                                                                                                             nb
                                                                                                                                                                                                                           ha ve th




                                                                                                                                                                               e
                                                                                                                                                                                                   sha                                eir own
                                        Consequences: Unique identifiers are assigned to each instance of the                                                                                         re                                                       instance                            methods
                                                                                                                                                                                                                                                               variables
                                        class for each execution of the program.                                                                                                                     class
                                                                                                                                                                                                   variables
                                        Related Patterns: This pattern makes use of the Instance Variable
                                        pattern.

                                        Java: Learning to Program with Robots                                 31                        Java: Learning to Program with Robots                                                                                                                             32
Summary




                                        We have learned:
                                           • how to test a class with its own main method.
                                           • about numeric types such as int and double, including their
                                             differing ranges and precision, converting between types,
                                             formatting, and shortcuts such as +=.
                                           • about non-numeric types, including boolean, char, String, and
                                             enumerated types.
                                           • how to use these types in a class that had nothing to do with robots.
                                           • about class variables and methods.
                                           • how to use a Java interface to make a class we write work with a
                                             class written by someone else, such as a graphic user interface.




                                        Java: Learning to Program with Robots                                 33

				
DOCUMENT INFO