跳到主要内容

使用对象与方法

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

本主题的视频课程 打开视频页面
15:05

使用对象和方法

这里有两个 Java 程序。第一个缺少分号。第二个将七除以二并将答案存储在整数中。编译器停止了…

英语旁白 · 英中内嵌字幕

1.1

算法、编程与编译器导论

教学大纲

学习目标 1.1.A: 使用书面语言或图表表示日常生活中的模式和算法。

  • 1.1.A.1 算法(Algorithms) 定义了完成任务或解决问题时遵循的逐步过程。这些算法可以使用书面语言或图表来表示。
  • 1.1.A.2 顺序(Sequencing) 定义了完成过程中各个步骤的顺序。过程中的步骤是按顺序逐一完成的。

学习目标 1.1.B: 解释代码编译和执行的过程。

  • 1.1.B.1 代码可以在任何文本编辑器中编写;但是,通常使用 集成开发环境(IDE, Integrated Development Environment) 来编写程序,因为它为程序员提供了编写、编译和运行代码的工具。
  • 1.1.B.2 编译器(Compiler) 检查代码中的某些错误。编译器能够检测到的错误必须在程序运行之前修复。

学习目标 1.1.C: 识别不同类型的编程错误。

  • 1.1.C.1 语法错误(Syntax error) 是程序中的错误,表现为未遵循编程语言规则。这类错误由编译器检测出来。
  • 1.1.C.2 逻辑错误(Logic error) 是算法或程序中的错误,导致其行为不正确或出乎意料。这类错误通过用特定数据测试程序并观察是否产生预期结果来发现。
  • 1.1.C.3 运行时错误(Run-time error) 是在程序执行过程中发生的错误。运行时错误通常会导致程序异常终止。
  • 1.1.C.4 异常(Exception) 是一种由于编译器未能检测到的意外错误而引发的运行时错误。它会中断程序执行的正常流程。

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

English
A Java source file with its class, main method and statement marked, beside the steps javac compiles and the JVM runs
A Java program: a class holds the main method, which holds the statements; javac compiles it to bytecode and the JVM runs it

An algorithm 算法 is a finite, step-by-step procedure that solves a problem. A program 程序 expresses an algorithm in a language a computer can run. Java is compiled 编译: the compiler 编译器 translates your source code into bytecode, which the Java Virtual Machine (JVM) runs. A syntax error 语法错误 (breaking the grammar) is caught by the compiler; a logic error 逻辑错误 (wrong result) is not – the program runs but misbehaves.

A compiler translates the whole program at once; an interpreter runs it line by line
A compiler translates the whole program at once; an interpreter runs it line by line
Several computer processor chips seen from below
Your Java program is compiled to instructions a CPU like one of these actually runs
词汇 训练
English 中文 拼音
algorithm/ˈælɡərɪθəm/ 算法 suàn fǎ
program/ˈprəʊɡræm/ 程序 chéng xù
compiled/kəmˈpaɪld/ 编译 biān yì
compiler/kəmˈpaɪlə/ 编译器 biān yì qì
syntax error/ˈsɪntæks ˈerə/ 语法错误 yǔ fǎ cuò wù
logic error/ˈlɒdʒɪk ˈerə/ 逻辑错误 luó jí cuò wù
1.2

变量与数据类型

教学大纲

学习目标 1.2.A: 为特定规范识别最合适的数据类型类别。

  • 1.2.A.1 数据类型是一组值以及针对这些值的一组相应操作。数据类型可分为基本类型或引用类型。
  • 1.2.A.2 本课程使用的 基本数据类型 定义了数值和布尔值的值集及其相应的操作集合。
  • 1.2.A.3 引用类型 用于定义非基本类型的对象。

学习目标 1.2.B: 编写代码以声明存储数值和布尔值的变量。

  • 1.2.B.1 本课程使用的三种基本数据类型是 int、double 和 boolean。int 值为整数,double 值为实数,boolean 值为 true 或 false。
    • 排除说明: 其他五个基本数据类型(long、short、byte、float 和 char)不属于 AP 计算机科学 A 课程及考试范围。
  • 1.2.B.2 变量 是一个存储位置,用于保存值,该值可在程序运行期间发生变化。每个变量都有一个名称和一个关联的数据类型。基本类型的变量保存来自该类型的基本值。

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

English

A variable 变量 is a named box that stores a value of a fixed type 类型. Java's main primitive types 基本类型 are int (whole numbers), double (decimals), and boolean (true/false). Declare with the type first:

Java's basic data types, each storing a different kind of value
Java's basic data types, each storing a different kind of value
int score = 90;
double price = 4.99;
boolean passed = true;
探索

探索变量如何同时只持有一个值

变量是一个存储固定类型的一个值的命名框。逐步执行各行代码并观察每个框取值;注意重新赋值 score 覆盖旧数字而不是创建一个新框。

词汇 训练
English 中文 拼音
variable/ˈveərɪəbl/ 变量 biàn liàng
type/taɪp/ 类型 lèi xíng
primitive types/ˈprɪmɪtɪv taɪps/ 基本类型 jī běn lèi xíng
1.3

表达式与输出

教学大纲

学习目标 1.3.A: 编写代码以生成输出并确定将显示的结果。

  • 1.3.A.1 System.out.print 和 System.out.println 在计算机屏幕上显示信息。System.out.println 在信息显示后会将光标移至新行,而 System.out.print 不会。

学习目标 1.3.B: 编写代码以使用字符串字面量并确定使用字符串字面量的结果。

  • 1.3.B.1 字面量(literal) 是固定值的代码表示形式。
  • 1.3.B.2 字符串字面量(string literal) 是用双引号括起来的字符序列。
  • 1.3.B.3 转义序列(escape sequences) 是可以包含在字符串中的特殊字符序列。它们以 \ 开头,在 Java 中具有特殊含义。本课程中使用的转义序列包括双引号 \"、反斜杠 \\ 和换行符 \n。

学习目标 1.3.C: 编写算术表达式代码并确定这些表达式的结果。

  • 1.3.C.1 算术表达式(arithmetic expressions) 由数值、变量和运算符组成,包括类型为 int 和 double 的表达式。
  • 1.3.C.2 算术运算符(arithmetic operators) 包括加法 +、减法 -、乘法 *、除法 / 和取余 %。使用两个 int 值进行的算术运算将求值为 int 值。使用至少一个 double 值进行的算术运算将求值为 double 值。
    • 排除说明: 产生特殊 double 值(例如无穷大和 NaN)的表达式不在 AP 计算机科学 A 课程和考试范围内。
  • 1.3.C.3 当对两个都是 int 类型的数值进行除法运算时,结果仅为商的整数部分。当对使用至少一个 double 值的数值进行除法运算时,结果为商。
  • 1.3.C.4 取余运算符 % 用于计算一个数 a 除以另一个数 b 时的余数。
    • 排除说明: 使用小于 0 的 a 值以及使用小于或等于 0 的 b 值不在 AP 计算机科学 A 课程和考试范围内。
  • 1.3.C.5 可以使用运算符构建复合表达式。在编译时,数值根据运算符优先级与运算符关联以确定其分组方式。可以使用括号修改运算符优先级。乘法、除法和取余运算的优先级高于加法和减法。具有相同优先级的运算符从左到右依次求值。
  • 1.3.C.6 尝试将整数除以整数零将导致 ArithmeticException 异常。
    • 排除说明: 当一个数值为 double 类型时进行除以零的操作不在 AP 计算机科学 A 课程和考试范围内。

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

English

An expression 表达式 combines values and operators to compute a result: + - * / and % (modulus 取模, the remainder). Integer division truncates: 7 / 2 is 3, while 7 % 2 is 1. Operator precedence follows math (*,/,% before +,-). Print with:

System.out.print("no newline");
System.out.println("with newline");

Dividing an integer by the integer 0 (like 7 / 0) is not allowed and crashes at run time with an ArithmeticException. Inside a string, a backslash marks an escape sequence 转义序列: \" prints a double quote, \\ a single backslash, and \n starts a new line – so System.out.println("She said \"hi\""); prints She said "hi".

print stays on the line, println ends it; + adds numbers until a String appears
print stays on the line, println ends it; + adds numbers until a String appears
探索

逐步探索运算顺序

Java 在 *、/、% 之前应用 + 和 -,从左到右进行。观察每一步,了解为什么 2 + 3 * 4 是 $14$ 而不是 $20$——乘法先执行。

词汇 训练
English 中文 拼音
expression/ekˈspreʃn/ 表达式 biǎo dá shì
modulus/ˈmɒdjʊləs/ 取模 qǔ mó
escape sequence/eˈskeɪp ˈsiːkwəns/ 转义序列 zhuǎn yì xù liè
1.4

赋值语句与输入

教学大纲

学习目标 1.4.A: 编写包含表达式的赋值语句代码,并确定这些语句执行后存储在变量中的值。

  • 1.4.A.1 在表达式中使用任何变量之前,必须先为其赋值。该值必须来自兼容的数据类型。变量在第一次被赋值时即被初始化。引用类型可以被赋予一个新对象或 null(如果没有对象的话)。字面量 null 是一个特殊值,用于表示引用未关联到任何对象。
  • 1.4.A.2 赋值运算符 = 允许程序初始化或修改变量中存储的值。右侧表达式的值将被存储在左侧的变量中。
    • 排除说明: 在表达式内部使用赋值运算符(例如 a = b = 4; 或 a[i += 5])超出了 AP 计算机科学 A 课程和考试的范围。
  • 1.4.A.3 在执行过程中,表达式会被求值以产生单个值。表达式的值具有基于该表达式求值结果的数据类型。

学习目标 1.4.B: 编写读取输入的代码。

  • 1.4.B.1 输入可以来自多种形式,例如触觉、音频、视觉或文本。Scanner 类是从键盘获取文本输入的一种方式。
    • 排除说明: 用户的任何特定形式的输入均超出 AP 计算机科学 A 课程和考试的范围。

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

English

An assignment 赋值 x = expr; evaluates the right side and stores it in the left variable. Read input with a Scanner:

Scanner in = new Scanner(System.in);
int age = in.nextInt();
String name = in.next();
Assignment copies a value into a variable's box; later changes to one variable do not affect the other
Assignment copies a value into a variable's box; later changes to one variable do not affect the other
词汇 训练
English 中文 拼音
assignment/əˈsaɪnmənt/ 赋值 fù zhí
1.5

类型转换与变量取值范围

教学大纲

学习目标是 1.5.A: 编写代码,在算术表达式中将原始数据类型值强制转换为不同的原始数据类型,并确定所产生的结果值。

  • 1.5.A.1 强制转换运算符 (int) 和 (double) 可用于将 double 类型的值转换为 int 类型的值(或反之)。
  • 1.5.A.2 将 double 类型的值强制转换为 int 类型的值会导致小数点右侧的数字被截断。
  • 1.5.A.3 某些代码会使 int 类型的值自动强制转换(拓宽)为 double 类型的值。
  • 1.5.A.4 对于非负数,类型为 double 的值可以通过 (int)(x + 0.5) 四舍五入到最接近的整数;对于负数,则通过 (int)(x - 0.5) 进行四舍五入。

学习目标是 1.5.B: 描述整数表达式求值超出取值范围的条件。

  • 1.5.B.1 常量 Integer.MAX_VALUE 保存最大可能的 int 值的值。常量 Integer.MIN_VALUE 保存最小可能的 int 值的值。
  • 1.5.B.2 Java 中的整数值由类型为 int 的值表示,这些值使用有限数量的内存(4 字节)存储。因此,int 类型的值必须在从 Integer.MIN_VALUE 到 Integer.MAX_VALUE(含端点)的范围内。
  • 1.5.B.3 如果表达式的求值结果超出了允许的 int 值范围,就会发生整数溢出。结果是处于允许范围内的 int 值,但不一定是预期的值。

学习目标是 1.5.C: 描述限制表达式精度的条件。

  • 1.5.C.1 计算机根据数据类型分配指定数量的内存来存储数据。如果表达式的求值结果是一个比分配内存所能存储的精度更高的 double 值,就会发生舍入误差。结果将被四舍五入为可表示的值。为避免自然发生的舍入误差,请使用 int 值。
    • 排除说明: 其他可用于避免舍入误差的特殊十进制数据类型不在 AP 计算机科学 A 课程和考试范围内。

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

English
int range, overflow and truncation

Each type has a fixed range; an int overflows past about 2.1 billion. Casting 类型转换 converts between types. Widening (int to double) is automatic; narrowing needs an explicit cast, which truncates (does not round):

double avg = (double) total / count;   // force real division
int whole = (int) 3.9;                 // 3, truncated

Exam skill: watch for integer division producing a truncated result when a decimal was expected – cast one operand to double first.

Worked example. Trace each expression:

  • 7 / 2 → 3 (both int, so division truncates);
  • 7.0 / 2 → 3.5 (one double forces real division);
  • 7 % 2 → 1 (the remainder);
  • (double) 7 / 2 → 3.5 (the cast binds tighter than /, so it is 7.0 / 2);
  • (double) (7 / 2) → 3.0 (the parentheses compute 7 / 2 = 3 in int first, then widen).

The last two look alike but differ – the position of the cast decides whether the truncation happens.

Casting truncates toward zero; int arithmetic overflows past Integer.MAX_VALUE
Casting truncates toward zero; int arithmetic overflows past Integer.MAX_VALUE
探索

为什么 int 和 double 以不同方式存储数字

int 仅存储固定范围内的整数;double 存储尾数和指数,以牺牲精确性为代价换取巨大的数值范围。将 double 转换为 int 会丢弃小数部分,而超出 int 范围的数值会发生溢出。

词汇 训练
English 中文 拼音
Casting/ˈkæstɪŋ/ 类型转换 lèi xíng zhuǎn huàn
1.6

复合赋值运算符

教学大纲

学习目标 1.6.A: 编写包含复合赋值运算符的赋值语句代码,并确定结果存储在变量中的值。

  • 1.6.A.1 复合赋值运算符 +=、-=、*=、/= 和 %= 可以替代数值表达式中的赋值运算符。复合赋值运算符会在左侧的值与右侧的值之间执行指定的算术运算,然后将结果赋值给左侧的变量。
  • 1.6.A.2 后置自增运算符 ++ 和后置自减运算符 -- 用于将数值变量的存储值加 1 或减 1。新值会被赋值给该变量。
    • 排除说明: 前缀形式的自增和自减运算符的使用(例如 ++x)不属于 AP 计算机科学 A 课程及考试的范围。在其他表达式内使用自增和自减运算符(例如 arr[x++])也不属于 AP 计算机科学 A 课程及考试的范围。

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

English

Shorthands combine an operation with assignment: x += 5 means x = x + 5; likewise -=, *=, /=, %=. The increment and decrement operators x++ and x-- add or subtract one.

Compound assignment operators traced on one variable
Compound assignment operators traced on one variable

Common mistakes.

  • x =+ 3; is not x += 3;: it reads as x = +3, so x becomes 3.
  • The integer-division rule still applies: with int x = 25;, x /= 4; gives 6, not 6.25.
  • x++; changes x itself; x + 1 on its own changes nothing and does not compile as a statement.
1.7

应用程序接口(API)与库

教学大纲

学习目标 1.7.A: 识别 API 所包含的库中类的属性和行为。

  • 1.7.A.1 库(Libraries)是类的集合。应用程序编程接口(API) 规范向程序员说明如何使用这些类。API 规范和库中的文档对于理解由 API 定义的类的属性和行为至关重要。类(Class)定义了一种特定的引用类型。API 和库中的类被组织在包(packages)中。可以利用现有的类和类库来创建对象。
  • 1.7.A.2 属性(Attributes)指与类相关的数据,存储在变量中。行为(Behaviors)指类的实例能做什么(或对其能做什么),由方法定义。

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

English

An API (Application Programming Interface) 应用程序接口 is the published list of classes and methods you may use. A library 库 is a collection of ready-made classes (like Math, String, Scanner). You read the API documentation to learn what a method needs (its parameters) and returns, without seeing its inner code – an example of abstraction 抽象.

A library groups classes; each class documents the methods you can call
A library groups classes; each class documents the methods you can call
词汇 训练
English 中文 拼音
library/ˈlaɪbrəri/ 库 kù
abstraction/əbˈstrækʃn/ 抽象 chōu xiàng
API/ˌeɪ piː ˈaɪ/ 应用程序接口 yìng yòng chéng xù jiē kǒu
1.8

用注释编写文档

教学大纲

学习目标 1.8.A: 描述通过注释来解释代码的功能和用途。

  • 1.8.A.1 注释(Comments) 是为原始程序员及其他程序员编写的,用于帮助理解代码及其功能;但编译器会忽略这些注释,且程序运行时不会执行它们。Java 中包含三种类型的注释:/* */,用于生成块级注释;//,用于生成单行注释;以及 /** */,即 Javadoc 注释,用于创建 API 文档。
  • 1.8.A.2 前置条件(precondition) 是指方法执行前必须为真的条件,以确保该方法能按预期行为运行。没有要求方法内部检查前置条件是否已满足。
  • 1.8.A.3 后置条件(postcondition) 是指方法执行后必须始终为真的条件。后置条件描述了执行的结果,具体体现为返回值或对象属性的当前值。

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

English

Comments 注释 are ignored by the compiler but explain code to humans: // for a single line, /* ... */ for a block, and /** ... */ for a Javadoc comment that documents a method's purpose, parameters, and return value. Precise preconditions and postconditions are written here.

A Javadoc comment above the method header public double mean(int a, int b): a sentence saying what it does, a precondition, an @param line for each parameter and an @return line for the result
A Javadoc comment: purpose, precondition, one @param per parameter, @return

A precondition 前置条件 is what must be true before the method is called (the caller's job); a postcondition 后置条件 is what the method guarantees afterwards. If a precondition is broken, the method is not required to work: mean(-3, 5) breaks the precondition that a and b are not negative, so its result is not promised.

词汇 训练
English 中文 拼音
Comments/ˈkɒments/ 注释 zhù shì
precondition 前置条件 qián zhì tiáo jiàn
postcondition 后置条件 hòu zhì tiáo jiàn
1.9

方法签名

教学大纲

学习目标 1.9.A: 根据文档和方法签名识别应调用的正确方法。

  • 1.9.A.1 方法(method) 是一个具有名称的代码块,仅在被调用时运行。代码块(block of code) 是指任何被花括号包围的代码部分。过程抽象(procedural abstraction) 允许程序员在了解方法功能的前提下使用方法,即使他们不知道该方法的具体实现方式。
  • 1.9.A.2 参数(parameter) 是在方法或构造函数的头部声明的变量,可以在方法体内部使用。这允许值和实参被传递并由方法或构造函数使用。对于带有参数的方法,其 方法签名(method signature) 由方法名和有序的参数类型列表组成。对于不带参数的方法,其方法签名由方法名和一个空参数列表组成。

学习目标 1.9.B: 描述如何调用方法。

  • 1.9.B.1 void 方法(void method) 没有返回值,因此不作为表达式的一部分被调用。
  • 1.9.B.2 非 void 方法(non-void method) 返回一个值,该值的类型与头部中声明的返回类型相同。要在调用非 void 方法时使用返回值,必须将其存储到变量中或作为表达式的一部分使用。
  • 1.9.B.3 实参(argument) 是方法被调用时传入的值。传递给方法的实参必须在数量和顺序上与签名中的参数列表所标识的类型兼容。在调用方法时,采用 传值调用(call by value) 的方式传递实参。传值调用(call by value) 通过用实参的副本初始化参数来实现。
  • 1.9.B.4 当存在多个名称相同但签名不同的方法时,这些方法被称为 重载(overloaded)。
  • 1.9.B.5 方法调用(method call) 会中断语句的顺序执行,导致程序首先执行该方法中的语句,然后再继续执行。一旦执行完方法中的最后一条语句或遇到 return 语句,控制流将返回到方法调用点之后的紧接着的位置。

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

English

A method signature 方法签名 is a method's name plus its parameter types, e.g. nextInt() or substring(int, int). To call a method you must supply arguments 实参 that match the parameters in number, type, and order. The method header (the full declaration) also states the return type – the type of value the method gives back (void if none) – but the return type is not part of the signature, which is why two methods cannot differ by return type alone.

Worked example. String has substring(int beginIndex, int endIndex) and indexOf(String str). For String w = "network";:

  • w.substring(2, 5) matches: two int arguments, returns "two";
  • w.substring("2", "5") does not compile: String arguments where int is required;
  • w.indexOf("work") matches: one String argument, returns 3;
  • int n = w.substring(3); does not compile: the method returns a String, which cannot be stored in an int.

Several methods with the same name but different parameter lists, such as the two substring methods, are overloaded 重载.

The parts of a method signature and a call that matches it
The parts of a method signature and a call that matches it
词汇 训练
English 中文 拼音
method signature/ˈmeθəd ˈsɪɡnɪtʃə/ 方法签名 fāng fǎ qiān míng
arguments/ˈɑːɡjuːmənts/ 实参 shí cān
overloaded 重载 zhòng zài
1.10

调用类方法

教学大纲

学习目标 1.10.A: 编写代码以调用类方法,并确定这些调用的结果。

  • 1.10.A.1 类方法与类本身相关联,而非类的实例。类方法的声明头部在方法名前包含关键字 static。
  • 1.10.A.2 类方法通常使用类名配合点运算符进行调用。当方法调用发生在定义该方法的类内部时,调用中省略类名是可选的。

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

English

A class (static) method 类方法 belongs to the class itself, so you call it on the class name: ClassName.method(args). No object is needed.

A class method is called on the class name: Math.sqrt(25.0)
A class method is called on the class name: Math.sqrt(25.0)

A void class method is a statement on its own; a non-void one returns a value that should be used:

double r = Math.sqrt(25.0);      // 5.0, stored
int big = Math.max(3, 8);        // 8
Math.sqrt(25.0);                 // compiles, but the result is lost

A class method that is called from inside its own class can be called by its name alone: average(a, b) instead of Stats.average(a, b).

探索

跟踪类方法调用栈

调用像 Math.max 这样的类方法会将一个新的帧压入调用栈;当方法返回一个值时,其帧弹出,控制权回到调用者。逐步执行以观察栈的增长和收缩。

词汇 训练
English 中文 拼音
class (static) method/klæs ˈmeθəd/ 类方法 lèi fāng fǎ
1.11

Math 类

教学大纲

学习目标 1.11.A: 编写代码,写出包含对内置数学库调用的表达式,并确定所产生的值。

  • 1.11.A.1 Math 类是 java.lang 包的一部分。java.lang 包中的类默认可用。
  • 1.11.A.2 Math 类仅包含类方法。以下 Math 类方法(包括其功能及使用时机)属于 Java 快速参考表:
    • static int abs(int x) 返回 int 值的绝对值。
    • static double abs(double x) 返回 double 值的绝对值。
    • static double pow(double base, double exponent) 返回第一个参数以第二个参数为指数的幂运算结果。
    • static double sqrt(double x) 返回 double 值的非负平方根。
    • static double random() 返回一个大于或等于 0.0 且小于 1.0 的 double 值。
  • 1.11.A.3 Math.random() 的返回值可以通过算术和强制类型转换运算符进行处理,从而根据指定条件生成指定范围内的随机 int 或 double 值。范围的每个端点可以是 包含 的,即该值被包含在内;也可以是 不包含 的,即该值不被包含在内。

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

English

The Math class provides static math methods: Math.abs(x), Math.pow(base, exp), Math.sqrt(x), and Math.random() (a double in $[0,1)$). To get a random integer from 0 to n-1: (int)(Math.random() * n).

Math.random() gives a value from 0.0 up to 1.0; multiplying by 6 stretches it from 0.0 up to 6.0; casting to int gives 0 to 5; adding 1 gives a whole number from 1 to 6, as the top value 1.0 is never reached
From Math.random() to a dice roll

For a whole number from low to high inclusive: (int) (Math.random() * (high - low + 1)) + low. The bracket high - low + 1 counts the values; the cast truncates; + low shifts the start.

Want Expression
a dice roll, 1 to 6 (int) (Math.random() * 6) + 1
10 to 20 (int) (Math.random() * 11) + 10
an even number 0 to 10 (int) (Math.random() * 6) * 2

Math.pow and Math.sqrt always return a double, so int p = Math.pow(2, 3); does not compile; (int) Math.pow(2, 3) gives 8. Casting before multiplying is a classic error: (int) Math.random() * 6 is always 0.

1.12

对象:类的实例

教学大纲

学习目标 1.12.A: 解释类与对象之间的关系。

  • 1.12.A.1 对象是类的一个具有特定属性的具体实例。类是对象属性和行为的正式实现或蓝图。
  • 1.12.A.2 可以通过将相关类的公共属性和行为放入一个称为超类(superclass)的单个类中,来构建类层次结构。扩展超类的类称为子类(subclasses),它们可以继承超类的现有属性和行为,而无需在代码中替换这些内容。这建立了从子类到超类的继承关系。
    • 排除说明: 设计并实现继承关系不在 AP 计算机科学 A 课程和考试范围内。
  • 1.12.A.3 Java 中的所有类都是 Object 类的子类。

学习目标 1.12.B: 编写代码以声明用于存储引用类型的变量。

  • 1.12.B.1 引用类型变量保存对象引用,可以将其视为该对象的内存地址。

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

English
= copies the reference, not the object

A class 类 is a blueprint; an object 对象 is a concrete instance 实例 built from it. A class bundles data (fields) with behavior (methods) – the heart of object-oriented programming 面向对象编程. String, Scanner, and ArrayList are all classes you instantiate.

Classes can be organised into a hierarchy. A superclass 父类 holds attributes and behaviors shared by several subclasses 子类 that extend it – an inheritance relationship 继承关系. Every class in Java is ultimately a subclass of the built-in Object class, which is why every object already has a toString method; writing a subclass method with the same signature as a superclass one is method overriding 方法重写. (Designing your own inheritance is beyond this course, but you are expected to recognise this vocabulary.)

A class diagram: private attributes and public methods
A class diagram: private attributes and public methods
A class is a blueprint; each object is one instance built from it
A class is a blueprint; each object is one instance built from it
词汇 训练
English 中文 拼音
class/klæs/ 类 lèi
object/ˈɒbdʒekt/ 对象 duì xiàng
instance/ˈɪnstəns/ 实例 shí lì
object-oriented programming/ˈɒbdʒekt ˈɔːrɪəntɪd ˈprəʊɡræmɪŋ/ 面向对象编程 miàn xiàng duì xiàng biān chéng
superclass/ˈsuːpəklæs/ 父类 fù lèi
subclasses/ˈsʌbklæsɪz/ 子类 zi lèi
inheritance relationship/ɪnˈherɪtəns rɪˈleɪʃənʃɪp/ 继承关系 jì chéng guān xì
method overriding/ˈmeθəd ˌəʊvəˈraɪdɪŋ/ 方法重写 fāng fǎ zhòng xiě
1.13

对象的创建与存储(实例化)

教学大纲

学习目标 1.13.A: 使用构造方法的签名识别正在调用的正确构造方法。

  • 1.13.A.1 类包含用于创建对象的 构造方法,其名称与类名相同。
  • 1.13.A.2 构造方法签名 由构造方法的名称(即类名)和有序的参数类型列表组成。参数列表位于构造方法的头部,列出了传入值的类型及其变量名。
  • 1.13.A.3 当存在多个具有不同签名的构造方法时,称这些构造方法被重载了。

学习目标 1.13.B: 编写代码以声明正确类型的变量来保存对象引用。

  • 1.13.B.1 引用类型的变量保存一个对象引用;如果不存在对象,则为 null。

学习目标 1.13.C: 编写代码通过调用构造方法来创建对象。

  • 1.13.C.1 通常使用关键字 new 后跟对类中某个构造方法的调用来创建对象。
  • 1.13.C.2 参数允许构造方法接受值,从而建立对象属性的初始值。
  • 1.13.C.3 构造方法实参 是在构造方法被调用时传入的值。传递给构造方法的实参必须在顺序和数量上与构造方法签名中的参数列表所标识的类型兼容。在调用构造方法时,采用按值传递方式传递实参。按值传递使用实参的副本初始化形参。
  • 1.13.C.4 构造方法调用会中断语句的顺序执行,使程序首先执行构造方法中的语句,然后再继续执行。一旦构造方法中的最后一条语句被执行,控制权将返回到紧接在构造方法调用点之后的位置。

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

English

Instantiation 实例化 creates an object with the new keyword, which calls a constructor 构造函数:

Scanner in = new Scanner(System.in);
String s = new String("hi");   // or just "hi"

The variable holds a reference 引用 (the object's address), not the object itself. Two references can point to the same object; comparing them with == compares addresses, not contents.

A reference can also point to nothing: the special value null 空值 means "not attached to any object". Calling a method on a null reference crashes at run time with a NullPointerException. Guard against it by testing with ==/!= and checking null first, so && short-circuits before the method runs: if (s != null && s.length() > 0).

A primitive variable holds its value directly, a reference holds an arrow to the object
A primitive variable holds its value directly, a reference holds an arrow to the object
词汇 训练
English 中文 拼音
Instantiation/ˌɪnstænʃɪˈeɪʃn/ 实例化 shí lì huà
constructor/kənˈstrʌktə/ 构造函数 gòu zào hán shù
reference/ˈrefrəns/ 引用 yǐn yòng
null/nʌl/ 空值 kōng zhí
1.14

调用实例方法

教学大纲

学习目标 1.14.A: 编写代码以调用实例方法并确定这些调用的结果。

  • 1.14.A.1 实例方法是在类的对象上被调用的。使用点运算符(dot operator)结合对象名称来调用实例方法。
  • 1.14.A.2 对 null 引用进行方法调用将导致 NullPointerException(空指针异常)。

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

English

An instance method 实例方法 acts on a specific object, so you call it on the object reference: object.method(args). Example: in.nextInt(), word.length().

The variable a refers to the String object "tiger", so a.length() is 5; the variable b holds null and refers to no object, so b.length() throws a NullPointerException
An instance method needs an object: on null it throws a NullPointerException

Worked example. A BankAccount class has deposit(double amt), withdraw(double amt) and getBalance().

BankAccount a = new BankAccount(100.0);
BankAccount b = a;                 // b refers to the SAME object
b.withdraw(30.0);
a.deposit(5.0);
System.out.println(a.getBalance() + " " + b.getBalance());

There is only one object, so both calls change it: $100 - 30 + 5 = 75$, and the output is 75.0 75.0. Each instance method acts on the object before the dot; with two separate new objects the balances would differ.

词汇 训练
English 中文 拼音
instance method/ˈɪnstəns ˈmeθəd/ 实例方法 shí lì fāng fǎ
1.15

字符串操作

教学大纲

学习目标 1.15.A: 编写代码以创建字符串对象并确定创建和组合字符串的结果。

  • 1.15.A.1 String 对象表示一个字符序列,可以通过使用字符串字面量或调用 String 类构造函数来创建。
  • 1.15.A.2 String 类属于 java.lang 包。java.lang 包中的类默认可用。
  • 1.15.A.3 String 对象是不可变的(immutable),这意味着一旦创建了 String 对象,其属性就无法更改。在 String 对象上调用的方法不会改变该 String 对象的内容。
  • 1.15.A.4 两个 String 对象可以使用 + 或 += 运算符连接或组合,从而生成一个新的 String 对象。基本类型值可以与 String 对象连接。这会导致基本类型值隐式转换为 String 对象。
  • 1.15.A.5 String 对象可以与任何对象连接,这将隐式调用该对象的 toString 方法(这是由每个类与 Object 类的继承关系所保证的行为)。对象的 toString 方法返回一个代表该对象的字符串值。Object 的子类通常会使用特定于类的实现来重写 toString 方法。方法重写(Method overriding)是指当子类中的公共方法与父类中的公共方法具有相同的方法签名,但该方法的行为是特定于子类时发生的情况。
    • 排除声明: 重写类的 toString 方法超出了 AP 计算机科学 A 课程和考试的范围。

学习目标 1.15.B: 编写代码以调用字符串对象上的方法并确定调用这些方法的结果。

  • 1.15.B.1 String 对象的索引值从 0 到字符串长度减 1。尝试访问超出此范围的索引将导致 StringIndexOutOfBoundsException。
  • 1.15.B.2 以下 String 方法——包括它们的功能和使用场景——属于 Java 快速参考的一部分:
    • int length() 返回 String 对象中字符的数量。
    • String substring(int from, int to) 返回从索引 from 开始、到索引 to - 1 结束的子字符串。
    • String substring(int from) 返回 substring(from, length())。
    • int indexOf(String str) 返回 str 首次出现的索引;如果未找到则返回 -1。
    • boolean equals(Object other) 如果 this 对应与 other 相同的字符序列则返回 true;否则返回 false。
    • int compareTo(String other) 如果 this 小于 other 则返回值 < 0;如果 this 等于 other 则返回零;如果 this 大于 other 则返回值 > 0。字符串按字母表顺序排序。
    • 排除声明: 使用 equals 方法将一个 String 对象与非 String 类型的对象进行比较超出了 AP 计算机科学 A 课程和考试的范围。
  • 1.15.B.3 可以通过调用 substring(index, index + 1) 来创建与位置 index 处的单个元素子字符串相同的字符串。

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

English
Strings are immutable

String objects are immutable 不可变 – methods return a new string rather than changing the original. Key methods (all indices start at 0):

s.length();            // number of characters
s.substring(2, 5);     // chars at index 2,3,4 (5 excluded)
s.indexOf("ab");       // first position, or -1
s.equals(other);       // content comparison (never use == for Strings)
s.compareTo(other);    // <0, 0, >0 by dictionary order

Exam skill: substring(a, b) includes index a but excludes b, and String comparison must use .equals, not == – two of the most-tested String pitfalls.

Worked example. Let String s = "COMPUTER"; (indices 0–7). Then s.length() is 8; s.substring(0, 4) is "COMP" (indices 0,1,2,3 – index 4 excluded); s.substring(4) is "UTER" (from index 4 to the end); s.indexOf("PU") is 3; and s.indexOf("X") is -1 (not found). Counting the excluded endpoint of substring is the single most common slip.

Asking for an index outside 0 to length()-1 (a bad substring or charAt argument, e.g. s.substring(0, 20) here) crashes with a StringIndexOutOfBoundsException – the String cousin of the array-index error.

String indices start at 0
String indices start at 0
探索

探索字符串索引和切片

每个字符都有一个索引,编号从0开始。拖动起始位置和结束位置,查看 substring(from, to) 如何获取从 from 开始到(但不包括)to 的字符。

词汇 训练
English 中文 拼音
immutable/ɪˈmjuːtəbl/ 不可变 bù kě biàn
1.15

考试技巧

English
  • Trace code by hand line by line, tracking each variable's value in a table — the exam rewards careful tracing over guessing.
  • Know Java's primitive types and that integer division truncates ($7/2$ gives $3$); use a cast or a double for real division.
  • Distinguish compile-time errors (syntax, types) from run-time errors – know the named ones: ArithmeticException (int ÷ 0), NullPointerException (method on a null reference), StringIndexOutOfBoundsException / ArrayIndexOutOfBoundsException – and logic errors (wrong output).
  • Follow operator precedence and initialise every variable before you use it.
  • On the free-response, write complete, compilable Java — return the right type and match the method header exactly.

该知识点的互动课程

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

历年真题

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

登录或创建账户

IGCSE, A-Level & AP