跳到主要内容

类的创建

AP 计算机科学 A · 第 3 主题

训练
讲义 词汇表
3.1

抽象与程序设计

大纲
Learning ObjectiveEssential Knowledge

3.1.A
Represent the design of a program by using natural language or creating diagrams that indicate the classes in the program and the data and procedural abstractions found in each class by including all attributes and behaviors.

  • 3.1.A.1 Abstraction is the process of reducing complexity by focusing on the main idea. By hiding details irrelevant to the question at hand and bringing together related and useful details, abstraction reduces complexity and allows one to focus on the idea.
  • 3.1.A.2 Data abstraction provides a separation between the abstract properties of a data type and the concrete details of its representation. Data abstraction manages complexity by giving data a name without referencing the specific details of the representation. Data can take the form of a single variable or a collection of data, such as in a class or a set of data.
  • 3.1.A.3 An attribute is a type of data abstraction that is defined in a class outside any method or constructor. An instance variable is an attribute whose value is unique to each instance of the class. A class variable is an attribute shared by all instances of the class.
  • 3.1.A.4 Procedural abstraction provides a name for a process and allows a method to be used only knowing what it does, not how it does it. Through method decomposition, a programmer breaks down larger behaviors of the class into smaller behaviors by creating methods to represent each individual smaller behavior. A procedural abstraction may extract shared features to generalize functionality instead of duplicating code. This allows for code reuse, which helps manage complexity.
  • 3.1.A.5 Using parameters allows procedures to be generalized, enabling the procedures to be reused with a range of input values or arguments.
  • 3.1.A.6 Using procedural abstraction in a program allows programmers to change the internals of a method (to make it faster, more efficient, use less storage, etc.) without needing to notify method users of the change as long as the method signature and what the method does is preserved.
  • 3.1.A.7 Prior to implementing a class, it is helpful to take time to design each class including its attributes and behaviors. This design can be represented using natural language or diagrams.

来源:美国大学理事会 AP 课程与考试说明

抽象(abstraction)意味着把细节隐藏在一个简单的接口之后——你使用一个 String 而不知道它如何存储字符。好的设计把一个问题分解成类,每个负责一个思想。这个主题是关于写你自己的类。

把一个程序分解成模块和子模块
把一个程序分解成模块和子模块
词汇表 训练
英文 中文 拼音
Abstraction 抽象 chōu xiàng
3.2

程序设计的影响

大纲
Learning ObjectiveEssential Knowledge

3.2.A
Explain the social and ethical implications of computing systems.

  • 3.2.A.1 System reliability refers to the program being able to perform its tasks as expected under stated conditions without failure. Programmers should make an effort to maximize system reliability by testing the program with a variety of conditions.
  • 3.2.A.2 The creation of programs has impacts on society, the economy, and culture. These impacts can be both beneficial and harmful. Programs meant to fill a need or solve a problem can have unintended harmful effects beyond their intended use.
  • 3.2.A.3 Legal issues and intellectual property concerns arise when creating programs. Programmers often reuse code written by others and published as open source and free to use. Incorporation of code that is not published as open source requires the programmer to obtain permission and often purchase the code before integrating it into their program.

来源:美国大学理事会 AP 课程与考试说明

设计选择影响代码是否正确、可读和可重用。封装(encapsulation)——保持数据私有并只通过方法暴露它——保护一个对象的状态免于误用,并让你在不破坏类的用户的情况下改变里面。深思熟虑的命名、单一目的的方法和测试减少 bug。

设计还承担着代码之外的责任。系统可靠性(system reliability) - 一个程序按预期完成任务、不出故障 - 是程序员应当通过精心的设计和测试去最大化的。程序对社会、经济和文化有真实的影响,这些影响既可以有益也可以有害。而且创造程序会引发法律和知识产权(intellectual property)方面的顾虑:程序员常常重用作为开源(open source)发布、可免费使用的代码,但必须尊重它的许可证并给出署名,而不是把他人的成果当作自己的来抄。

词汇表 训练
英文 中文 拼音
Encapsulation 封装 fēng zhuāng
System reliability 系统可靠性 xì tǒng kě kào xìng
legal and intellectual-property 知识产权 zhī shí chǎn quán
open source 开源 kāi yuán
3.3

类的结构剖析

大纲
Learning ObjectiveEssential Knowledge

3.3.A
Develop code to designate access and visibility constraints to classes, data, constructors, and methods.

  • 3.3.A.1 Data encapsulation is a technique in which the implementation details of a class are kept hidden from external classes. The keywords public and private affect the access of classes, data, constructors, and methods. The keyword private restricts access to the declaring class, while the keyword public allows access from classes outside the declaring class.
  • 3.3.A.2 In this course, classes are always designated public and are declared with the keyword class.
  • 3.3.A.3 In this course, constructors are always designated public.
  • 3.3.A.4 Instance variables belong to the object, and each object has its own copy of the variable.
  • 3.3.A.5 Access to attributes should be kept internal to the class in order to accomplish encapsulation. Therefore, it is good programming practice to designate the instance variables for these attributes as private unless the class specification states otherwise.
  • 3.3.A.6 Access to behaviors can be internal or external to the class. Methods designated as public can be accessed internally or externally to a class, whereas methods designated as private can only be accessed internally to the class.

来源:美国大学理事会 AP 课程与考试说明

一个类有三个部分:实例变量(instance variables)(字段——对象的数据)、构造函数(constructors)(构建对象),和方法(methods)(行为)。字段通常是 private;方法通常是 public:

一个类图:私有属性和公有方法
一个类图:私有属性和公有方法
public class Student {
    private String name;      // instance variable
    private int score;

    public Student(String n, int s) {   // constructor
        name = n;
        score = s;
    }
    public int getScore() { return score; }   // accessor
}
A blueprint: a class is a template that defines how objects of that type are built
A blueprint: a class is a template that defines how objects of that type are built
探索

See an object's fields as boxes

A class groups related data (its fields) and methods. Each object gets its own set of field boxes; assigning to one changes that object only.

词汇表 训练
英文 中文 拼音
instance variables 实例变量 shí lì biàn liàng
constructor 构造函数 gòu zào hán shù
accessor (getter) 访问器 fǎng wèn qì
3.4

构造方法

大纲
Learning ObjectiveEssential Knowledge

3.4.A
Develop code to declare instance variables for the attributes to be initialized in the body of the constructors of a class.

  • 3.4.A.1 An object's state refers to its attributes and their values at a given time and is defined by instance variables belonging to the object. This defines a has-a relationship between the object and its instance variables.
  • 3.4.A.2 A constructor is used to set the initial state of an object, which should include initial values for all instance variables. When a constructor is called, memory is allocated for the object and the associated object reference is returned. Constructor parameters, if specified, provide data to initialize instance variables.
  • 3.4.A.3 When a mutable object is a constructor parameter, the instance variable should be initialized with a copy of the referenced object. In this way, the instance variable does not hold a reference to the original object, and methods are prevented from modifying the state of the original object.
  • 3.4.A.4 When no constructor is written, Java provides a no-parameter constructor, and the instance variables are set to default values according to the data type of the attribute. This constructor is called the default constructor.
  • 3.4.A.5 The default value for an attribute of type int is 0. The default value of an attribute of type double is 0.0. The default value of an attribute of type boolean is false. The default value of a reference type is null.

来源:美国大学理事会 AP 课程与考试说明

一个构造函数(constructor)有与类相同的名字且没有返回类型。它在你写 new 时运行,而它的工作是初始化字段。一个类能有几个带不同参数列表的构造函数(重载(overloading));一个无参数构造函数设置默认值。

词汇表 训练
英文 中文 拼音
overloading 重载 zhòng zài
3.5

方法:如何编写

大纲
Learning ObjectiveEssential Knowledge

3.5.A
Develop code to define behaviors of an object through methods written in a class using primitive values and determine the result of calling these methods.

  • 3.5.A.1 A void method does not return a value. Its header contains the keyword void before the method name.
  • 3.5.A.2 A non-void method returns a single value. Its header includes the return type in place of the keyword void.
  • 3.5.A.3 In non-void methods, a return expression compatible with the return type is evaluated, and the value is returned. This is referred to as return by value.
  • 3.5.A.4 The return keyword is used to return the flow of control to the point where the method or constructor was called. Any code that is sequentially after a return statement will never be executed. Executing a return statement inside a selection or iteration statement will halt the statement and exit the method or constructor.
  • 3.5.A.5 An accessor method allows objects of other classes to obtain a copy of the value of instance variables or class variables. An accessor method is a non-void method.
  • 3.5.A.6 A mutator (modifier) method is a method that changes the values of the instance variables or class variables. A mutator method is often a void method.
  • 3.5.A.7 Methods with parameters receive values through those parameters and use those values in accomplishing the method's task.
  • 3.5.A.8 When an argument is a primitive value, the parameter is initialized with a copy of that value. Changes to the parameter have no effect on the corresponding argument.

来源:美国大学理事会 AP 课程与考试说明

一个方法有一个签名、一个返回类型和一个主体。一个访问器(getter)(accessor)返回信息而不改变对象;一个修改器(setter)(mutator)改变一个字段。一个返回一个值的方法必须在每条路径上有一个正确类型的 return;一个 void 方法什么都不返回。

public void setScore(int s) { score = s; }   // mutator
public String toString() { return name + ": " + score; }
探索

Follow a method call and its return

Calling a method pushes a frame with its parameters; when it hits return, the frame pops and the value goes back to the caller.

词汇表 训练
英文 中文 拼音
mutator (setter) 修改器 xiū gǎi qì
3.6

方法:传递与返回对象引用

大纲
Learning ObjectiveEssential Knowledge

3.6.A
Develop code to define behaviors of an object through methods written in a class using object references and determine the result of calling these methods.

  • 3.6.A.1 When an argument is an object reference, the parameter is initialized with a copy of that reference; it does not create a new independent copy of the object. If the parameter refers to a mutable object, the method or constructor can use this reference to alter the state of the object. It is good programming practice to not modify mutable objects that are passed as parameters unless required in the specification.
  • 3.6.A.2 When the return expression evaluates to an object reference, the reference is returned, not a reference to a new copy of the object.
  • 3.6.A.3 Methods cannot access the private data and methods of a parameter that holds a reference to an object unless the parameter is the same type as the method's enclosing class.

来源:美国大学理事会 AP 课程与考试说明

= 复制的是引用,不是对象

当你把一个对象传给一个方法时,Java 复制引用,所以方法作用于同一个对象——对它字段的变化对调用者可见。(基本类型按值复制,所以对它们的变化不可见。)一个方法也能返回一个对象的引用。因为一个 String 是不可变的,传一个是安全的;传一个可变的对象让一个方法能改变它。

Java 按值传递:方法得到一个副本;真正的按引用传递(Java 没有)会让它重新赋值调用者的变量
Java 总是按值传递(左):方法得到引用的一个副本。真正的按引用传递(右)——Java 没有——会让一个方法重新赋值调用者自己的变量。

考试技能: 知道在一个方法里面改变一个对象的字段影响原来的,但重新赋值参数(param = new...)不影响调用者。

Worked example. 假设 s 是一个分数为 50Student,而我们调用 tweak(s):

public static void tweak(Student a) {
    a.setScore(100);          // (1) mutates the shared object
    a = new Student("Z", 0);  // (2) repoints the local copy only
    a.setScore(5);            // (3) changes only the new local object
}

第 (1) 行改变 s 指向的对象,所以调用者现在看到 100。第 (2) 行使方法自己的引用副本指向一个新的对象——调用者的 s 不受影响——而第 (3) 行只影响那个新对象。调用之后,s.getScore()100:改变留住了,重新赋值没有。

3.7

类变量与类方法

大纲
Learning ObjectiveEssential Knowledge

3.7.A
Develop code to define behaviors of a class through class methods.

  • 3.7.A.1 Class methods cannot access or change the values of instance variables or call instance methods without being passed an instance of the class via a parameter.
  • 3.7.A.2 Class methods can access or change the values of class variables and can call other class methods.

3.7.B
Develop code to declare the class variables that belong to the class.

  • 3.7.B.1 Class variables belong to the class, with all objects of a class sharing a single copy of the class variable. Class variables are designated with the static keyword before the variable type.
  • 3.7.B.2 Class variables that are designated public are accessed outside of the class by using the class name and the dot operator, since they are associated with a class, not objects of a class.
  • 3.7.B.3 When a variable is declared final, its value cannot be modified.

来源:美国大学理事会 AP 课程与考试说明

静态成员与实例成员

一个静态(类)变量(static (class) variable),标记 static,被类的所有对象共享——总共一个副本(例如一个存在多少对象的计数器)。一个静态方法属于类而不能直接使用实例字段。按类名访问它们:Student.getCount()

词汇表 训练
英文 中文 拼音
static (class) variable 类变量 lèi biàn liàng
3.8

作用域与访问权限

大纲
Learning ObjectiveEssential Knowledge

3.8.A
Explain where variables can be used in the code.

  • 3.8.A.1 Local variables are variables declared in the headers or bodies of blocks of code. Local variables can only be accessed in the block in which they are declared. Since constructors and methods are blocks of code, parameters to constructors or methods are also considered local variables. These variables may only be used within the constructor or method and cannot be declared to be public or private.
  • 3.8.A.2 When there is a local variable or parameter with the same name as an instance variable, the variable name will refer to the local variable instead of the instance variable within the body of the constructor or method.

来源:美国大学理事会 AP 课程与考试说明

作用域(scope)是一个名字可见的地方。一个在一个方法里声明的局部变量(local variable)只在它里面存在;一个参数(parameter)只在它的方法里存在;一个实例变量(instance variable)在整个对象里可见。访问修饰符控制跨类的可见性:private(只这个类)与 public(任何地方)。局部变量遮蔽(shadow)同名的字段——一个 bug 的来源。

一个全局变量处处可见;一个局部变量只在它的块里面
一个全局变量处处可见;一个局部变量只在它的块里面
词汇表 训练
英文 中文 拼音
Scope 作用域 zuò yòng yù
3.9

this 关键字

大纲
Learning ObjectiveEssential Knowledge

3.9.A
Develop code for expressions that are self-referencing and determine the result of these expressions.

  • 3.9.A.1 Within an instance method or a constructor, the keyword this acts as a special variable that holds a reference to the current object—the object whose method or constructor is being called.
  • 3.9.A.2 The keyword this can be used to pass the current object as an argument in a method call.
  • 3.9.A.3 Class methods do not have a this reference.

来源:美国大学理事会 AP 课程与考试说明

this 是对当前对象的一个引用。用它来把一个字段与一个同名的参数区分开,或调用同一对象的另一个方法:

public Student(String name, int score) {
    this.name = name;      // this.name is the field; name is the parameter
    this.score = score;
}

考试技能: 当一个构造函数或 setter 的参数与一个字段同名时,你必须this.field = param ——没有 this,赋值什么有用的都不做。

3.9

考试技巧

  • 用方法和类设计:把数据封装为 private 字段并通过公有方法暴露行为。
  • 知道一个对象和它的之间的差别,以及对象按值传递——参数得到引用的一个副本,所以一个方法能改变对象的状态,但重新赋值参数不影响调用者(Java 没有按引用传递)。
  • 安全地遍历数组和 ArrayList ——大小是 length vs .size(),而在一个循环期间移除会移动索引。
  • 跟踪一个递归方法以确定它的结果:先找到基本情况,然后沿着每次递归调用到它的返回值(写递归代码不在考试范围内)。
  • 认识继承词汇——超类、子类、方法重写,以及每个类都是 Object 的子类(设计和实现继承不在考试范围内)。

本主题的互动课程

逐步学习,并即时检测练习。

AP 计算机科学 A历年真题

AP 计算机科学 A的更多主题

登录或创建账号

IGCSE, A-Level & AP