跳到主要内容

类的创建

AP 计算机科学 A · 知识点 3

本主题的视频课程 打开视频页面
7:26

类创建

这里有一个学生,存储为三个松散变量:姓名、年级和成绩。这可以工作。现在添加一千名学生。你需要三千个变量…

英语旁白 · 英中内嵌字幕

3.1

抽象与程序设计

教学大纲

学习目标 3.1.A: 使用自然语言或创建图表来表示程序设计,图表中应指出程序中的类以及每个类中发现的数据和过程抽象,并包含所有属性和行为。

  • 3.1.A.1 抽象(Abstraction) 是通过关注核心思想来降低复杂性的过程。通过隐藏与当前问题无关的细节,并将相关且有用的细节整合在一起,抽象降低了复杂性,使人们能够专注于核心思想。
  • 3.1.A.2 数据抽象(Data abstraction) 提供了数据类型抽象属性与其表示具体细节之间的分离。数据抽象通过给数据命名而不引用表示的具体细节来管理复杂性。数据可以表现为单个变量,也可以表现为数据的集合,例如在类或数据集的形式中。
  • 3.1.A.3 属性(Attribute) 是一种定义在类中、位于任何方法或构造器之外的数据抽象类型。实例变量(Instance variable) 是值对于类的每个实例都唯一的属性。类变量(Class variable) 是被该类的所有实例共享的属性。
  • 3.1.A.4 过程抽象(Procedural abstraction) 为过程提供一个名称,使得方法的使用者只需知道它做什么,而无需了解它是如何实现的。通过 方法分解(Method decomposition),程序员通过将类较大的行为拆分为较小的行为,并为每个独立的较小行为创建方法来表示,从而实现这一目标。过程抽象可以提取共享特征以泛化功能,而不是复制代码。这允许代码复用,有助于管理复杂性。
  • 3.1.A.5 使用参数可以使过程被泛化,从而允许过程在一组输入值或参数下被重复使用。
  • 3.1.A.6 在程序中使用过程抽象允许程序员修改方法的内部实现(使其更快、更高效、占用更少存储空间等),只要保留了方法签名和方法的功能,就不需要通知方法使用者这些更改。
  • 3.1.A.7 在实现类之前,花时间为每个类进行设计(包括其属性和行为)是很有帮助的。这种设计可以使用自然语言或图表来表示。

来源:College Board AP 课程与考试说明

English
A jigsaw in progress: classes and methods are modular pieces of a larger program design
A jigsaw in progress: classes and methods are modular pieces of a larger program design

Abstraction 抽象 means hiding detail behind a simple interface 接口 – you use a String without knowing how it stores characters. Good design breaks a problem into classes, each responsible for one idea. This topic is about writing your own classes.

Decomposing a program into modules and sub-modules
Decomposing a program into modules and sub-modules
词汇 训练
English 中文 拼音
Abstraction/əbˈstrækʃn/ 抽象 chōu xiàng
interface/ˈɪntəfeɪs/ 接口 jiē kǒu
3.2

程序设计的影响

教学大纲

学习目标 3.2.A: 解释计算系统的社会与伦理影响。

  • 3.2.A.1 系统可靠性是指程序能够在声明的条件下按预期执行任务而不发生失败的能力。程序员应通过在各种条件下测试程序,努力最大限度地提高系统可靠性。
  • 3.2.A.2 程序的创建对社会、经济和文化都会产生影响。这些影响既可能是有益的,也可能是有害的。旨在满足需求或解决问题的程序,在其预期用途之外也可能产生意想不到的有害后果。
  • 3.2.A.3 在创建程序时会出现法律问题及知识产权方面的担忧。程序员经常复用他人编写并作为开源且免费使用的代码。如果整合的代码未以开源形式发布,程序员通常需要获得许可,并且往往需要在将其集成到程序中之前购买该代码的使用权。

来源:College Board AP 课程与考试说明

English

Design choices affect whether code is correct, readable 可读的, and reusable 可复用的. Encapsulation 封装 – keeping data private 私有的 and exposing it only through methods 方法 – protects an object's state 状态 from misuse and lets you change the inside without breaking users of the class. Thoughtful naming, single-purpose methods, and testing 测试 reduce bugs 缺陷.

Design also carries responsibility beyond the code. System reliability 系统可靠性 - a program performing its tasks as expected, without failure - is something programmers should maximise through careful design and testing. Programs have real impacts on society, the economy, and culture that can be both beneficial 有益的 and harmful 有害的. And creating programs raises legal 法律 and intellectual-property 知识产权 concerns: programmers often reuse code published as open source 开源 and free to use, but must respect its licence 许可证 and give credit 注明出处 rather than copy others' work as their own.

词汇 训练
English 中文 拼音
readable 可读的 kě dú de
reusable/riːˈjuːzəbl/ 可复用的 kě fù yòng de
Encapsulation/ɪnˌkæpsjʊˈleɪʃn/ 封装 fēng zhuāng
private/ˈpraɪvət/ 私有的 sī yǒu de
methods/ˈmeθədz/ 方法 fāng fǎ
state/steɪt/ 状态 zhuàng tài
testing/ˈtestɪŋ/ 测试 cè shì
bugs 缺陷 quē xiàn
System reliability/ˈsɪstəm rɪˌlaɪəˈbɪlɪti/ 系统可靠性 xì tǒng kě kào xìng
beneficial/ˌbenɪˈfɪʃl/ 有益的 yǒu yì de
harmful/ˈhɑːmfl/ 有害的 yǒu hài de
legal/ˈliːɡl/ 法律 fǎ lǜ
intellectual-property 知识产权 zhī shí chǎn quán
open source/ˈəʊpən sɔːs/ 开源 kāi yuán
licence/ˈlaɪsəns/ 许可证 xǔ kě zhèng
give credit 注明出处 zhù míng chū chù
3.3

类的结构剖析

教学大纲

学习目标 3.3.A: 编写代码,为类、数据、构造方法和方法指定访问和可见性约束。

  • 3.3.A.1 数据封装是一种将类的实现细节对外部类隐藏的技术。关键字 public 和 private 影响类、数据、构造方法和方法的访问权限。关键字 private 限制访问仅限于声明它的类内部,而关键字 public 允许从声明类外部的类进行访问。
  • 3.3.A.2 在本课程中,类始终被指定为 public,并使用关键字 class 进行声明。
  • 3.3.A.3 在本课程中,构造方法始终被指定为 public。
  • 3.3.A.4 实例变量属于对象,每个对象都有该变量的独立副本。
  • 3.3.A.5 为了实现封装,对属性的访问应保持在类内部。因此,除非类规范另有说明,否则良好的编程实践是将这些属性的实例变量指定为 private。
  • 3.3.A.6 对行为的访问可以是类内部的也可以是类外部的。被指定为 public 的方法可以在类内部或外部被访问,而被指定为 private 的方法只能在类内部被访问。

来源:College Board AP 课程与考试说明

English

A class has three parts: instance variables 实例变量 (fields 字段 – the object's data), constructors (build objects), and methods (behavior 行为). Fields are usually private; methods are usually public:

A class diagram: private attributes and public methods
A class diagram: private attributes and public methods
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

Common mistake. Repeating the type inside the constructor declares a new local variable instead of setting the field:

public Student(String n, int s) {
    String name = n;   // local variable: the field name stays null
    score = s;         // correct: sets the field
}

The code compiles, but every Student built this way has name equal to null.

探索

将对象的字段视为盒子

类将相关数据(其字段)和方法进行分组。每个对象拥有自己的一组字段框;对一个对象的赋值仅改变该对象。

词汇 训练
English 中文 拼音
instance variables/ˈɪnstəns ˈveərɪəblz/ 实例变量 shí lì biàn liàng
fields 字段 zì duàn
behavior/bɪˈheɪvjə/ 行为 xíng wéi
3.4

构造方法

教学大纲

学习目标 3.4.A: 编写代码以声明实例变量,用于初始化类构造方法体中所需的属性。

  • 3.4.A.1 对象的状态(state)是指其在特定时间点的属性及其值,由属于该对象的实例变量定义。这定义了对象与其实例变量之间的has-a关系。
  • 3.4.A.2 构造方法用于设置对象的初始状态,其中应包含所有实例变量的初始值。当调用构造方法时,系统会为该对象分配内存并返回相关的对象引用。如果指定了构造方法参数,则提供用于初始化实例变量的数据。
  • 3.4.A.3 当可变对象作为构造方法的参数时,实例变量应以对该引用对象的副本进行初始化。通过这种方式,实例变量不会持有对原始对象的引用,从而防止方法修改原始对象的状态。
  • 3.4.A.4 如果未编写任何构造方法,Java 会提供一个无参构造方法,并且实例变量会根据属性的数据类型被设置为默认值。该构造方法称为默认构造方法(default constructor)。
  • 3.4.A.5 int 类型属性的默认值为 0。double 类型属性的默认值为 0.0。boolean 类型属性的默认值为 false。引用类型的默认值为 null。

来源:College Board AP 课程与考试说明

English

A constructor 构造函数 has the same name as the class and no return type 返回类型. It runs when you write new, and its job is to initialize 初始化 the fields. A class can have several constructors with different parameter lists 形参列表 (overloading 重载); a no-argument 无参 constructor accepts no arguments and can choose suitable defaults 默认值. Before constructor assignments, instance fields have Java’s type-dependent initial values, such as 0 for int and null for references.

Worked example. A Point class with two constructors:

public class Point {
    private int x, y;

    public Point() {             // no-argument: the origin
        x = 0;
        y = 0;
    }
    public Point(int a, int b) { // two int parameters
        x = a;
        y = b;
    }
}
Call Constructor used Fields
new Point() no-argument x = 0, y = 0
new Point(3, 4) (int, int) x = 3, y = 4
new Point(3) none matches does not compile

A field that a constructor does not set keeps its default value: 0 for int, 0.0 for double, false for boolean and null for an object. Writing public void Point() makes a method, not a constructor: a constructor has no return type, not even void.

词汇 训练
English 中文 拼音
constructor/kənˈstrʌktə/ 构造函数 gòu zào hán shù
return type 返回类型 fǎn huí lèi xíng
initialize 初始化 chū shǐ huà
parameter lists 形参列表 xíng cān liè biǎo
overloading/ˌəʊvəˈləʊdɪŋ/ 重载 zhòng zài
no-argument 无参 wú cān
defaults 默认值 mò rèn zhí
3.5

方法:如何编写

教学大纲

学习目标 3.5.A: 通过类中编写的方法,使用基本数据类型定义对象的行为并开发代码,同时确定调用这些方法的结果。

  • 3.5.A.1 void 方法不返回值。其方法头在方法名前包含关键字 void。
  • 3.5.A.2 非 void 方法返回单个值。其方法头用返回类型代替关键字 void。
  • 3.5.A.3 在非 void 方法中,会求值一个与返回类型兼容的 return 表达式,并返回该值。这被称为 按值返回 (return by value)。
  • 3.5.A.4 return 关键字用于将控制流返回到调用该方法或构造函数的位置。任何位于 return 语句之后的顺序代码都永远不会被执行。在选择或迭代语句内部执行 return 语句将会终止该语句并退出该方法或构造函数。
  • 3.5.A.5 访问器方法 (accessor method) 允许其他类的对象获取实例变量或类变量值的副本。访问器方法是一种非 void 方法。
  • 3.5.A.6 变通器(修改)方法 (mutator/modifier method) 是改变实例变量或类变量值的方法。变通器方法通常是 void 方法。
  • 3.5.A.7 带有参数的方法通过这些参数接收值,并使用这些值来完成方法的任务。
  • 3.5.A.8 当实参是一个基本数据类型值时,形参会被初始化为该值的副本。对形参的更改不会影响相应的实参。

来源:College Board AP 课程与考试说明

English

A method has a signature 方法签名, a return type, and a body 方法体. An accessor (getter) 访问器 returns information without changing the object; a mutator (setter) 修改器 changes a field. A method returning a value must have a return of the right type on every path; a void method returns nothing.

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

Worked example. Write a mutator addBonus(int b) that adds b to the score but never lets it go above 100, and returns the new score.

public int addBonus(int b) {
    score += b;
    if (score > 100) {
        score = 100;
    }
    return score;
}
  1. The return type is int, because the method gives back the new score.
  2. The parameter b is used; the field score is changed, so this is a mutator.
  3. For a score of 90, addBonus(15) sets the score to 100 and returns 100.

A common mistake is a return inside the if only: if (score > 100) { return 100; } with nothing after it does not compile, because the other path returns nothing. Another is printing the answer instead of returning it: a method asked to return a value must not just System.out.println it.

探索

跟踪方法调用及其返回值

调用方法会将其参数压入一个帧;当遇到 return 时,该帧弹出并将值返回给调用者。

词汇 训练
English 中文 拼音
signature/ˈsɪɡnɪtʃə/ 方法签名 fāng fǎ qiān míng
body/ˈbɒdi/ 方法体 fāng fǎ tǐ
accessor (getter)/əkˈsesə/ 访问器 fǎng wèn qì
mutator (setter)/mjuːˈteɪtə/ 修改器 xiū gǎi qì
3.6

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

教学大纲

学习目标 3.6.A: 编写代码,通过在类中使用对象引用来定义对象的行为,并确定调用这些方法的结果。

  • 3.6.A.1 当实参是对象引用时,形参被初始化为该引用的副本;它并不会创建该对象的一个全新的独立副本。如果形参指向一个可变对象,则该方法或构造函数可以使用此引用来修改该对象的状态。除非规范明确要求,否则良好的编程习惯是不修改作为参数传入的可变对象。
  • 3.6.A.2 当返回表达式求值结果为对象引用时,返回的是该引用,而不是新复制对象的一个引用。
  • 3.6.A.3 除非持有对象引用的参数的类型与方法所属的类相同,否则方法无法访问该参数的私有数据和私有方法。

来源:College Board AP 课程与考试说明

English
= copies the reference, not the object

When you pass an object to a method, Java copies the reference 引用, so the method acts on the same object – changes to its fields are visible to the caller 调用者. (Primitives 基本类型 are copied by value 按值复制, so changes to them are not.) A method can also return a reference to an object. Because a String is immutable 不可变, passing one is safe; passing a mutable 可变 object lets a method change it.

Java passes by value: the method gets a copy; true pass by reference, which Java lacks, would let it reassign the caller's variable
Java always passes by value (left): the method gets a copy of the reference. True pass by reference (right) — which Java does not have — would let a method reassign the caller's own variable.

Exam skill: know that mutating an object's fields inside a method affects the original, but reassigning the parameter (param = new...) does not affect the caller.

Worked example. Suppose s is a Student with score 50, and we call 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
}

Line (1) changes the object s points to, so the caller now sees 100. Line (2) makes the method's own copy of the reference point at a fresh object – the caller's s is untouched – and line (3) affects only that new object. After the call, s.getScore() is 100: the mutation stuck, the reassignment did not.

词汇 训练
English 中文 拼音
reference/ˈrefrəns/ 引用 yǐn yòng
caller 调用者 diào yòng zhě
Primitives/ˈprɪmɪtɪvz/ 基本类型 jī běn lèi xíng
copied by value 按值复制 àn zhí fù zhì
immutable/ɪˈmjuːtəbl/ 不可变 bù kě biàn
mutable 可变 kě biàn
3.7

类变量与类方法

教学大纲

学习目标 3.7.A: 编写代码,通过类方法来定义类的行为。

  • 3.7.A.1 如果没有通过参数传递该类的实例,类方法将无法访问或修改变量的值,也无法调用实例方法。
  • 3.7.A.2 类方法可以访问或修改变量的值,也可以调用其他类方法。

学习目标 3.7.B: 编写代码,声明属于该类的类变量。

  • 3.7.B.1 类变量属于该类,同一类的所有对象共享一份类变量的副本。类变量在变量类型前使用 static 关键字进行修饰。
  • 3.7.B.2 被指定为 public 的类变量可以通过类名和点运算符(dot operator)在类外部进行访问,因为它们关联的是类本身,而非类的具体对象。
  • 3.7.B.3 当变量被声明为 final 时,其值将无法被修改。

来源:College Board AP 课程与考试说明

English
static vs instance fields

A static (class) variable 类变量, marked static, is shared by all objects of the class – one copy total (e.g. a counter of how many objects exist). A static method 静态方法 belongs to the class and cannot use instance fields directly. Access them by class name: Student.getCount().

Worked example. Give each new Ticket a number, counting up from 1:

public class Ticket {
    private static int count = 0;   // one copy, shared
    private int number;             // one per object

    public Ticket() {
        count++;
        number = count;
    }
    public int getNumber() { return number; }
    public static int getCount() { return count; }
}

After Ticket a = new Ticket(); Ticket b = new Ticket(); Ticket c = new Ticket();, a.getNumber() is 1, c.getNumber() is 3 and Ticket.getCount() is 3. If count were not static, each object would have its own count, every ticket would be number 1, and getCount could not be static.

词汇 训练
English 中文 拼音
static (class) variable/ˈstætɪk ˈveərɪəbl/ 类变量 lèi biàn liàng
static method/ˈstætɪk ˈmeθəd/ 静态方法 jìng tài fāng fǎ
3.8

作用域与访问权限

教学大纲

学习目标 3.8.A: 解释变量可以在代码的哪些位置使用。

  • 3.8.A.1 局部变量 是在代码块(block)的头部或主体中声明的变量。局部变量只能在声明它的代码块中被访问。由于构造方法和方法是代码块,因此构造方法和方法的参数也被视为局部变量。这些变量只能在构造方法或方法内部使用,且不能将其声明为 public 或 private。
  • 3.8.A.2 当存在一个与实例变量同名的局部变量或参数时,在构造方法或方法的主体内,该变量名将指向局部变量而非实例变量。

来源:College Board AP 课程与考试说明

English

Scope 作用域 is where a name is visible. A local variable 局部变量 declared in a method exists only inside it; a parameter 形参 exists only in its method; an instance variable is visible throughout the object. Access modifiers 访问修饰符 control visibility 可见性 across classes: private (this class only) versus public (anywhere). Local variables shadow 遮蔽 fields of the same name – a source of bugs.

Worked example. Find the bug:

public void setScore(int score) {
    score = score;
}

The parameter score shadows the field, so both sides mean the parameter: the method copies the parameter onto itself and the field never changes. The fix is this.score = score; (see the next section) or a different parameter name such as newScore.

Name Declared in Visible in
instance variable the class, outside methods every method of the class
parameter the method header that method only
local variable a method or block from its line to the end of its block
loop variable in for (int i …) the for header that loop only
A global variable is visible everywhere; a local variable only inside its block
A global variable is visible everywhere; a local variable only inside its block
词汇 训练
English 中文 拼音
Scope/skəʊp/ 作用域 zuò yòng yù
local variable/ˈləʊkl ˈveərɪəbl/ 局部变量 jú bù biàn liàng
parameter/pəˈræmɪtə/ 形参 xíng cān
Access modifiers 访问修饰符 fǎng wèn xiū shì fú
visibility 可见性 kě jiàn xìng
shadow/ˈʃædəʊ/ 遮蔽 zhē bì
3.9

this 关键字

教学大纲

学习目标 3.9.A: 编写引用自身的表达式代码,并确定这些表达式的结果。

  • 3.9.A.1 在实例方法或构造器中,this 关键字充当一个特殊变量,它保存了对当前对象的引用——即正在调用该方法或构造器的对象。
  • 3.9.A.2 this 关键字可用于将当前对象作为参数传递给方法调用。
  • 3.9.A.3 类方法没有 this 引用。

来源:College Board AP 课程与考试说明

English

this is a reference to the current object 当前对象. Use it to tell a field apart from a parameter with the same name, or to call another method of the same object:

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

Exam skill: when a constructor or setter's parameter has the same name as a field, you must write this.field = param – without this, the assignment does nothing useful.

词汇 训练
English 中文 拼音
current object 当前对象 dāng qián duì xiàng
3.9

考试技巧

English
  • Design with methods and classes: encapsulate data as private fields and expose behaviour through public methods.
  • Know the difference between an object and its class, and that objects are passed by value — the parameter gets a copy of the reference, so a method can change the object's state, but reassigning the parameter does not affect the caller (Java has no pass-by-reference).
  • Traverse arrays and ArrayLists safely — size is length vs .size(), and removing during a loop shifts indices.
  • Trace a recursive method to determine its result: find the base case 基本情况 first, then follow each recursive call 递归调用 to its return value (writing recursive code is outside the exam's scope).
  • Recognise inheritance 继承 vocabulary — superclass 父类, subclass 子类, method overriding 方法重写, and that every Java class other than Object is a direct or indirect subclass of Object (designing and implementing inheritance is outside the exam's scope).
词汇 训练
English 中文 拼音
base case/beɪs keɪs/ 基本情况 jī běn qíng kuàng
recursive call/rɪˈkɜːsɪv kɔːl/ 递归调用 dì guī diào yòng
inheritance/ɪnˈherɪtəns/ 继承 jì chéng
superclass/ˈsuːpəklæs/ 父类 fù lèi
subclass/ˈsʌbklæs/ 子类 zi lèi
method overriding/ˈmeθəd ˌəʊvəˈraɪdɪŋ/ 方法重写 fāng fǎ zhòng xiě

该知识点的互动课程

逐步完成,配合即时检查练习。

历年真题

更多 AP 计算机科学 A 知识点

登录或创建账户

IGCSE, A-Level & AP