Skip to content

Class Creation

AP Computer Science A · Topic 3

Train
3.1

Abstraction and Program Design

Syllabus
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.

Source: College Board AP Course and Exam Description

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

Vocabulary Train
English Chinese Pinyin
Abstraction 抽象 chōu xiàng
3.2

The Impact of Program Design

Syllabus
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.

Source: College Board AP Course and Exam Description

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.

Vocabulary Train
English Chinese Pinyin
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

The Anatomy of a Class

Syllabus
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.

Source: College Board AP Course and Exam Description

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
}
Explore

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.

Vocabulary Train
English Chinese Pinyin
instance variables 实例变量 shí lì biàn liàng
3.4

Constructors

Syllabus
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.

Source: College Board AP Course and Exam Description

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 sets defaults.

Vocabulary Train
English Chinese Pinyin
constructor 构造函数 gòu zào hán shù
overloading 重载 zhòng zài
3.5

Methods: How to Write Them

Syllabus
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.

Source: College Board AP Course and Exam Description

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; }
Explore

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.

Vocabulary Train
English Chinese Pinyin
accessor (getter) 访问器 fǎng wèn qì
mutator (setter) 修改器 xiū gǎi qì
3.6

Passing and Returning References of an Object

Syllabus
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.

Source: College Board AP Course and Exam Description

= 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.

Pass by value gives a copy; pass by reference lets the method change the original Pass by value gives a copy; pass by reference lets the method change the original

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.

3.7

Class Variables and Class Methods

Syllabus
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.

Source: College Board AP Course and Exam Description

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().

Vocabulary Train
English Chinese Pinyin
static (class) variable 类变量 lèi biàn liàng
3.8

Scope and Access

Syllabus
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.

Source: College Board AP Course and Exam Description

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.

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

Vocabulary Train
English Chinese Pinyin
Scope 作用域 zuò yòng yù
3.9

The this Keyword

Syllabus
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.

Source: College Board AP Course and Exam Description

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.

3.9

Exam tips

  • 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 reference (a method can change the object's state).
  • Traverse arrays and ArrayLists safely — size is length vs .size(), and removing during a loop shifts indices.
  • Write and trace a recursive method: find the base case first, then check the recursive call moves toward it.
  • Use inheritance and polymorphism (override, super) so the right method runs at run time.

Log in or create account

IGCSE & A-Level