Documentation

The Java™ Tutorials
Hide TOC
Questions and Exercises问题和练习
Trail: Learning the Java Language
Lesson: Classes and Objects

Questions and Exercises: Classes问题和练习:类

Questions问题

  1. Consider the following class:考虑下面的类:

    public class IdentifyMyParts {
        public static int x = 7; 
        public int y = 3; 
    }
    1. What are the class variables?什么是类变量?x

    2. What are the instance variables?实例变量是什么?y

    3. 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);

Exercises练习

  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.您可以使用assert语句检查分配。You write:你写道:

    assert (boolean expression to test);

    If the boolean expression is false, you will get an error message.如果布尔表达式为false,则会收到错误消息。For example,例如

    assert toString(ACE) == "Ace";

    should return true, so there will be no error message.应返回true,因此不会出现错误消息。

    If you use the assert statement, you must run your program with the ea flag:如果使用assert语句,则必须使用ea标志运行程序:

    java -ea YourProgram.class

  2. Write a class whose instances represent a full deck of cards.编写一个类,其实例表示一整套卡片。You should also keep this solution.您还应该保留此解决方案。

  3. 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.该程序可以简单到创建一副卡片并显示其卡片。

Check your answers.检查你的答案。


Previous page: Summary of Creating and Using Classes and Objects
Next page: Questions and Exercises: Objects