CS111 PreLab 11

Task 1: Object Diagrams

Consider the following class definition:
public class ListNode {
  public int head;
  public ListNode tail;

  public ListNode (int h, ListNode x) {
    this.head = h;
    this.tail = x;
  }
}
Following the guidelines given for drawing Object Diagrams in Problem Set 8, Task 1, draw the object diagram that results from the following sequence of statements:
ListNode L1 = new ListNode(1,
                new ListNode(2,
                  new ListNode(3,
                    null);
ListNode L2 = new ListNode(4,
                new ListNode(5,
                  null);

L2.tail.tail = L1.tail;
L1.tail.tail.head = L2.head;
ListNode L3 = L2.tail.tail;
L3.tail.tail = L1;
L2.tail.head = L1.head + 2*L2.tail.tail.tail.tail.head;
Keep in mind that Object Diagrams are not the same as the Box-and-Pointer diagrams we have been using lately.


Task 2: Understanding Constructors

The core of the Card class being used in Problem Set 8, Task 2 is shown below.

public class Card {

  // Public Instance Variables
  public int value;
  public int suit;

  // Public Constructors

  // Creates a blank card with no value and no suit.
  public Card () {
    this.value = 0;
    this.suit = 0;
  }

  // Creates a card with the specified value and suit.
  public Card (int value, int suit) {
    this.value = value;
    this.suit = suit;
  }

}

Here are some things to note about the Card implementation: Given the above Card implementation (i.e. with two public instance variables value and suit), there are four possible ways to write a constructor which lets us set the value and suit of the Card when we create the card. The four implementations are shown below:
// Version 1
public Card (int value, int suit) {
  this.value = value;
  this.suit = suit;
}

// Version 2
public Card (int value, int suit) {
  value = value;
  suit = suit;
}

// Version 3
public Card (int v, int s) {
  this.value = v;
  this.suit = s;
}

// Version 4
public Card (int v, int s) {
  value = v;
  suit = s;
}
Draw a JEM showing the execution of the following testCard method using each of the implementations of the Card constructor above.
public static void testCard () {
  Card c = new Card(Card.TWO, Card.DIAMONDS);
}
Which constructors work and which don't, and why?