RU beehive logo ITEC Department logo
ITEC 120
2007spring
ibarland,
jpittges

homeinfoexamslectureslabshws
RecipeLawsliessyntaxjava.lang docsjava.util docs

lect09c
Practice with references
lect09c (references as values, continued)

Reading: Chapter 4.

We have seen there is a difference between two Cats which are different yet look the same, vs. two references to the identically same Cat.
Review question How do we test for the first version of equality? How about for identically-equal?

Suppose we have the following class:

class Cat {
  /** The name of this Cat. */
  String name;
  /** The age of this Cat, in years. */
  int age;

  /** Constructor.
    * @param _name This cat's name (to engrave on its collar).
    * @param _age  This cat's age, in (complete) years.
    */
  Cat( String _name, int _age ) {
    this.name = _name;
    this.age  = _age;
    }

  // Getters and setters omitted.
  }

  1. Write the following method, which belongs inside class Cat:
      /** Does this Cat look *just* like another?  (Has the same name and age?)
       * @param other The cat to compare this one to.
       * @return true if (and only if) these two cats *look* alike:
       *   If they have the same age, and the same name *ignoring case*.
       */
      boolean looksJustLike( Cat other ) { 
        // As per The Design Recipe, let's list what pieces of info we have to work with:
        // Only `this' and `other'.  
        // These are both of type                 .
        //  The pertinent methods we can call on each of these are                  and                 .
    
        }
      
    Optional: Suppose we want to modify this method so that it does pay attention to the case of the names (that is, a Cat named “Bartok” would not be considered to look just like a cat named “bartok”). In this case, we would need to change equalsIgnoreCase to a different String method named “.equals”.
    Challenge:
  2. If a cat gets cloned, are the clone and the original one and the same? (That is, if the clone dyes its hair blue, will the original have blue hair?)
    Should that cat and their clone be == to each other? Should they looksJustLike each other?
  3. Look at the following method. What does it do?
      /** THIS METHOD DOES NOT WORK AS DESIRED:
        * @return a new Cat which looks just this Cat, but is different.
        */
      Cat badClone() {
        return this;   // What gets returned?
        }
    

    Draw a picture of the objects involved, in the following test code:
    Cat c1    = new Cat( "socks", 4 );
    Cat c1_v2 = c1.badClone();
    
    c1 == c1_v2   // true or false?
    
    You can type the above into BlueJ's Code Pad, to confirm your hypothesis.
  4. Complete the following method.
      /**   
       * @return a new Cat which looks just like this Cat.
       */
      Cat goodClone() {
        // ... WRITE THIS METHOD ...
        // (hint: to create a new Cat which doesn't already exist, you must use ‘new’.)
        
    
        // (Note: were we to use the name "clone()", Java would force us
        // to include a mysterious word, "public".  We'll just skirt that
        // for now by naming the method goodClone().  It won't make 
        // sense to discuss "public" until we have two different classes
        // in the same project.)
        }
    
    Draw a picture of what happens, when you call goodClone instead of badClone in the above test code?

    By the way, note that some people feel there are good reasons to avoid implementing clone, due to the danger of an object and its clone sharing state. For instance, if we clone an entire Kennel, will the clone contain identically the same Dogs as the original? Or, will it contain clones of those Dogs? What about any String or Date objects?

  5. First, draw pictures of what needs happening, in the test cases. Then, complete the code following method.
      /**
       * @param partner the cat who is breeding with this.
       * @return a new kitten, whose age is 0 and whose name is a blend 
       *    of this's and partner's names.
       *    For example:
       *    Cat c1 = new Cat( "socks", 4 );
       *    Cat stray = new Cat( "kitty", 6 );
       *    c1.breed(stray) = new Cat( "sotty", 0 );
       *    stray.breed(c1) = new Cat( "kicks", 0 );
       *    (new Cat("garfield",4)).breed( new Cat("", 6) ) = new Cat( "garf", 0 );
       */
      Cat breed( Cat partner ) {
        // ... WRITE THIS METHOD ...
        
        }
    
    Assume the following method has been provided:
    String blend( String word1, String word2 )
    Returns a word which is the blend of two given words: the first half of the first word, followed by the second half of the second word.

    Examples:

    blend( "Information", "Technology") returns "Inforology"
    blend( "PuffDaddy", "Microsoft") returns "Puffosoft"

  6. Optional You look through Java's documentation for class String, and it turns out blend is not a standard library function. We'll have to write it ourself. But looking over the documentation did reveal the following helpful String methods: In figuring out this function, notice the two sub-components which were even mentioned in the problem: “the first half of word1” — how can you calculate that? How about “the second half of word2”? (If you like, use local variables to name these sub-results.)
    int length()
    Returns the length of this string.
    String substring(int beginIndex, int endIndex)
    Returns a new string that is a substring of this string. The substring begins at the specified beginIndex and extends to the character at index endIndex - 1. Thus the length of the substring is endIndex-beginIndex.

    Examples:

    "hamburger".substring(4, 8) returns "urge"
    "smiles".substring(1, 5) returns "mile"

    String concat( String str )
    Concatenates the specified string to the end of this string.
    Write blend2.
    Challenge problem: Given that Strings are objects, draw what happens when the following method is called:
     
    boolean testBlend() {
      String s1 = "George";
      String s2 = "Bush";
      String s3 = this.blend(s2,s3);
      return s3.equals("Geosh");
      }
    

    Can you combine the last two lines of this test, not using s3?
    Can you actually write this test using only one line in the body? Should we use == instead of .equals?

1Okay, if you are really sure that you want to test for two String-references both referring to the identically-same String, then use ==, but that is virtually never the case.      

2 This method blend is a behavior which really has nothing to do with Cats. But Java forces us to put every method inside a class, and class Cat is the only class we have, at the moment! We'd like to add this method to class String, but we're not allowed to modify that class.      

homeinfoexamslectureslabshws
RecipeLawsliessyntaxjava.lang docsjava.util docs


©2007, Ian Barland, Radford University
Last modified 2007.Aug.27 (Mon)
Please mail any suggestions
(incl. typos, broken links)
to iba�rlandrad�ford.edu
Powered by PLT Scheme