FANDOM


QuestionsEdit

  1. Consider the following class:
    public class IdentifyMyParts {
         public static int x = 7; 
         public int y = 3; 
    }

a. What are the class variables?

b. What are the instance variables?

c. What is the output from the following code:

       IdentifyMyParts a = new IdentifyMyParts();
       IdentifyMyParts b = new IdentifyMyParts();
       a.y = 5;
       b.y = 6;
       a.x = 1;
       b.x = 2;
       System.out.println("a.y = " + a.y);
       System.out.println("b.y = " + b.y);
       System.out.println("a.x = " + a.x);
       System.out.println("b.x = " + b.x);
       System.out.println("IdentifyMyParts.x = " + IdentifyMyParts.x);

ExercisesEdit

  1. Write a class whose instances represent a single playing card from a deck of cards. Playing cards have two distinguishing properties: rank and suit. Be sure to keep your solution as you will be asked to rewrite it in Enum Types.

Hint:

You can use the assert statement to check your assignments. You write:

 assert (boolean expression to test);

If the boolean expression is false, you will get an error message. For example,

 assert toString(ACE) == "Ace";

should return true, so there will be no error message.

If you use the assert statement, you must run your program with the ea flag:

 java -ea YourProgram.class
  1. Write a class whose instances represent a full deck of cards. You should also keep this solution.
  2. Write a small program to test your deck and card classes. The program can be as simple as creating a deck of cards and displaying its cards.

Answers to QuestionsEdit

1a. x

1b. y

1c. Here is a output.

    a.y = 5 
    b.y = 6 
    a.x = 2 
    b.x = 2
    IdentifyMyParts.x = 2

Because x is defined as a public static int in the class IdentifyMyParts, every reference to x will have the value that was last assigned because x is a static variable (and therefore a class variable) shared across all instances of the class. That is, there is only one x: when the value of x changes in any instance it affects the value of x for all instances of IdentifyMyParts.

This is covered in the Class Variables section of Understanding Instance and Class Members.

Answers to ExercisesEdit

  1. Card.java
  2. Desk.java
  3. DisplayDeck.java
Community content is available under CC-BY-SA unless otherwise noted.