← All Units← 返回单元列表 ← Course Hub← 课程主页
A P  C O M P U T E R  S C I E N C E  A
Unit 3 · Class Creation第 3 单元 · 类的创建

Class Creation类的创建

AP-Style MC & Free-Response PracticeAP 风格选择题与自由回答题练习

MEDIUM HARD AP MC AP FRQ

Unit 3: Class Creation第 3 单元:类的创建CSA



Name:姓名:Date:日期:
MULTIPLE CHOICE15 questions · ~32 min at exam pace15 道题 · 考试节奏约 32 分钟

Multiple Choice选择题(Multiple Choice)

Choose the best of the four options. Assume all referenced classes and methods are imported / available unless otherwise stated. "Consider the following code segment" implies the code compiles and runs without exception unless the question states otherwise.从四个选项中选择最合适的一个。除非另有说明,假定所有引用的类(class)与方法(method)均已导入且可用。"Consider the following code segment"("考虑以下代码段")默认代码可以正常编译并运行(不抛出异常),除非题目另有说明。

Q1MEDIUM AP MC 3.9 this Keyword [1]

Consider the following constructor.考虑以下构造方法(constructor)。

public class Box {
  private int size;
  public Box(int size) {
    this.size = size;
  }
}

What does the statement this.size = size; do?语句 this.size = size; 的作用是什么?

Q2MEDIUM AP MC 3.7 static Variables [1]

Which of the following statements about a static variable declared in a Java class is true?下列关于 Java 类中 static 变量的描述,哪一项是正确的?

Q3MEDIUM AP MC 3.4 Default Constructor [1]

Consider a Java class that declares no constructors of its own. Which of the following is true?假设某个 Java 类没有声明任何自定义的构造方法(constructor)。下列哪一项是正确的?

Q4HARD AP MC 3.6 Aliasing + compound assignment [1]

Consider the following class and code.考虑以下类与代码。

public class Box {
  public int n;
  public Box(int n) { this.n = n; }
}

// in main:
Box a = new Box(5);
Box b = a;
b.n = 10;
a.n += b.n;
System.out.println(a.n + " " + b.n);

What is printed?输出是什么?(注意 b = a; 之后 a 与 b 是别名 aliasing,指向同一个对象。)

Q5HARD AP MC 3.7 static aggregate + instance mutator [1]

Consider the following class.考虑以下类。

public class Sensor {
  private static int total = 0;
  private int reading;
  public Sensor(int r) { reading = r; total += r; }
  public void update(int r) {
    total -= reading;
    reading = r;
    total += r;
  }
  public static int total() { return total; }
}

// in main:
Sensor s1 = new Sensor(10);
Sensor s2 = new Sensor(20);
s1.update(50);
s2.update(0);
System.out.println(Sensor.total());

What is printed?输出是什么?(注意 static 聚合变量与实例修改器 mutator 在每次 update 中如何维持总和。)

Q6HARD AP MC 3.8 Missing this. Trap [1]

Consider the following class.考虑以下类。

public class Point {
  private int x;
  public Point(int x) {
    x = x;        // note: no this.
  }
  public int getX() { return x; }
}

// in main:
Point p = new Point(7);
System.out.println(p.getX());

What is printed (or what happens)?输出是什么(或会发生什么)?(注意构造方法中没有写 this.。)

Q7HARD AP MC 3.6 Reassigning a ref param vs mutating [1]

Consider the following class and methods.考虑以下类与方法。

public class Box {
  public int n;
  public Box(int n) { this.n = n; }
}

public static void replace(Box b) {
  b = new Box(99);
}

public static void mutate(Box b) {
  b.n = 99;
}

// in main:
Box one = new Box(1);
Box two = new Box(2);
replace(one);
mutate(two);
System.out.println(one.n + " " + two.n);

What is printed?输出是什么?(关键区别:replace 重新赋值本地引用 reassign reference,mutate 通过引用就地修改对象 mutate via reference。)

Q8HARD AP MC 3.5 Mutator order with conditional cap [1]

Consider the following class.考虑以下类。

public class Score {
  private int v;
  public Score(int v) { this.v = v; }
  public void add(int n) { v += n; }
  public void cap(int max) { if (v > max) v = max; }
  public int get() { return v; }
}

Score s = new Score(10);
s.add(20);
s.cap(15);
s.add(5);
s.cap(50);
System.out.println(s.get());

What is printed?输出是什么?(按顺序逐步执行每个修改器调用,注意 cap 仅当超过 max 时才裁剪。)

Q9HARD AP MC 3.5 Fluent interface (return this) [1]

Consider the following class.考虑以下类。

public class Counter {
  private int n;
  public Counter()       { n = 0; }
  public Counter inc()   { n++; return this; }
  public Counter dec()   { n--; return this; }
  public int peek()      { return n; }
}

Counter c = new Counter();
int x = c.inc().inc().inc().dec().peek();
System.out.println(x + " " + c.peek());

What is printed?输出是什么?(每个修改器 return this;,构成链式接口 fluent interface,所有方法调用作用于同一个对象。)

Q10HARD AP MC 3.6 Object Equality (==) [1]

Consider the following class and code.考虑以下类与代码。

public class Pt {
  public int x, y;
  public Pt(int x, int y) { this.x = x; this.y = y; }
}

Pt p = new Pt(1, 2);
Pt q = new Pt(1, 2);
Pt r = p;
System.out.println((p == q) + " " + (p == r));

What is printed?输出是什么?(提示:== 比较对象的引用地址 reference equality,而不是字段值。)

Q11HARD AP MC 3.8 Local Variable Shadows [1]

Consider the following class.考虑以下类。

public class Tank {
  private int level = 100;
  public void drain() {
    int level = 0;     // local declaration
    level -= 10;
  }
  public int getLevel() { return level; }
}

Tank t = new Tank();
t.drain();
System.out.println(t.getLevel());

What is printed?输出是什么?(注意 drain 中重新声明了局部 level,会"遮蔽" shadow 同名实例变量。)

Q12HARD AP MC 3.7 static Accessing Instance [1]

Consider the following class declaration.考虑以下类的声明。

public class Counter {
  private int count = 0;
  public static int getCount() {
    return count;
  }
}

What is the result of attempting to compile and run this class?尝试编译并运行此类的结果是什么?

Q13HARD AP MC 3.3 Encapsulation Access [1]

Consider the following class.考虑以下类。

public class Person {
  private String name;
  public Person(String name) { this.name = name; }
}

From a different class in the same package, a programmer writes:在同一个包中的另一个类里,某程序员写下:

Person p = new Person("Alice");
p.name = "Bob";   // line X

What happens at line X?在 line X 处会发生什么?(提示:private 字段的可见性 visibility。)

Q14HARD AP MC 3.6 Primitive vs Object Params [1]

Consider the following class and code.考虑以下类与代码。

public class Wrap {
  public int n;
  public Wrap(int n) { this.n = n; }
}

public static void modify(int x, Wrap w) {
  x   = 999;
  w.n = 999;
}

// in main:
int x = 5;
Wrap w = new Wrap(5);
modify(x, w);
System.out.println(x + " " + w.n);

What is printed?输出是什么?(提示:基本类型按值传递 pass by value,对象引用传的是地址副本——可以通过它修改对象,但重新赋值给参数本身不影响调用方。)

Q15HARD AP MC 3.7 static seq + aliasing + toString [1]

Consider the following class and code.考虑以下类与代码。

public class Tag {
  private static int seq = 0;
  private String label;
  private int id;
  public Tag(String label) {
    this.label = label;
    this.id = ++seq;
  }
  public String toString() { return "#" + id + ":" + label; }
}

// in main:
Tag a = new Tag("alpha");
Tag b = new Tag("beta");
Tag c = a;
a = new Tag("alpha");
System.out.println(a + " " + b + " " + c);

What is printed?输出是什么?(注意每个构造方法都会预增 ++seq,然后注意 c = a; 此时 a 仍然指向哪个对象。)

FREE RESPONSE1 question · ~25 min at exam pace1 道题 · 考试节奏约 25 分钟

Free-Response Question自由回答题(Free Response)

Write all program segments in Java. Unless stated otherwise, assume that parameters are not null and that methods are called only when their preconditions are satisfied. On the exam this is Question 2: Class Design, worth 7 points in a single part.所有程序段均用 Java 编写。除非另有说明,假定各参数不为 null,且方法仅在其前置条件(precondition)满足时被调用。在正式考试中,本题对应第 2 题:类的设计(Class Design),只有一小题,共 7 分。

FRQ 2HARD CLASS DESIGN 3.3 / 3.4 / 3.5 / 3.8 [7 pts]

A vending machine is made up of independent slots. Each slot sells copies of a single item at a fixed price and keeps a running total of the money it has taken in. You will write a complete VendingSlot class to represent one such slot. All prices and amounts of money are whole numbers of cents.一台自动售货机由若干彼此独立的货道组成。每条货道以固定价格出售同一种商品,并持续累计自己已收取的金额。你需要编写一个完整的 VendingSlot 类来表示这样一条货道。所有价格与金额均为整数分(cent)。

A slot must keep track of exactly three things, and none of them may be readable or writable from outside the class:每条货道必须恰好记录以下三项内容,且它们都不得能够从类的外部被读取或修改:

The class must support exactly the following constructor and method.该类必须恰好支持下列构造方法与方法。

Constructor / Method构造方法 / 方法 Description说明
VendingSlot(String itemName,
    int unitPrice)
Creates a slot that sells the item called itemName at unitPrice cents each. A newly created slot has collected no money at all.
Precondition: unitPrice >= 0.
创建一条货道,以每件 unitPrice 分的价格出售名为 itemName 的商品。新创建的货道尚未收取任何金额。
前置条件:unitPrice >= 0。
int sell(int quantity) Records the sale of quantity items from this slot.
The cost of the sale is quantity multiplied by the slot’s unit price. The method adds that cost to the total money this slot has collected, and returns the cost.
Precondition: quantity >= 0.
记录本货道售出 quantity 件商品这一笔交易。
本笔交易的金额为 quantity 与该货道单价之积。该方法把这笔金额累加到货道已收取的总金额中,并返回这笔金额。
前置条件:quantity >= 0。

The following table shows the required behavior for a slot created by VendingSlot slot = new VendingSlot("Pretzels", 125); when the calls are made in the order shown.下表给出由 VendingSlot slot = new VendingSlot("Pretzels", 125); 创建的货道,在按表中顺序依次调用时所要求的行为。

Statement语句 Value returned返回值 Total money collected afterwards执行后已收取的总金额
(just after construction)(刚创建时)—0
slot.sell(2)250250
slot.sell(1)125375
slot.sell(0)0375
slot.sell(4)500875
7 pts分 Write the complete VendingSlot class. Your implementation must include the class header, all necessary instance variables, the constructor, and the sell method, and must produce the results shown in the table.编写完整的 VendingSlot 类。你的实现必须包含类头、所有必要的实例变量、上述构造方法以及 sell 方法,并且必须产生表中所示的结果。

The money collected accumulates across calls — each sale adds to the previous total rather than replacing it. Note also that sell returns the cost of that one sale, not the running total.已收取的金额在多次调用之间不断累积 — 每笔交易都是在此前总额的基础上增加,而非将其覆盖。另请注意,sell 返回的是该单笔交易的金额,而不是累计总额。