Skip to content · ⁨コンテンツへスキップ⁩

Class Creation · ⁨クラス定義⁩

AP Computer Science A · ⁨APコンピュータサイエンスA⁩ · Topic 3 · ⁨トピック 3⁩

View Slides · ⁨查看幻灯片⁩ Train · ⁨練習する⁩
Video lesson for this topic · ⁨このトピックのビデオレッスン⁩ Open the video page · ⁨動画ページを開く⁩
7:26

クラス定義

aquí hay un estudiante, almacenado como tres variables sueltas: un nombre, un año y una calificación. Eso funciona. Ahora añade mil estudiantes. Necesitas tres mil variables…

English narration · English + 中文 subtitles burned in · ⁨英語ナレーション・英語+中文字幕 burning-in⁩

3.1

Abstraction and Program Design · ⁨アブストラクションとプログラム設計⁩

Syllabus · ⁨シラバス⁩
English

Learning Objective 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.
日本語

学習目標 3.1.A: 自然言語を使用するか、クラス図を作成することでプログラムの設計を表現する。図には、各クラスに含まれるデータおよび手続的抽象化(すべての属性と振る舞いを含む)を示す必要がある。

  • 3.1.A.1 抽象化 は、主要な概念に焦点を当てることで複雑さを軽減するプロセスである。現在の質問に関連しない詳細を隠し、関連して有用な詳細をまとめすることで、抽象化は複雑さを軽減し、概念への集中を可能にする。
  • 3.1.A.2 データ抽象化 は、データ型の抽象的特性とその表現の具体的な詳細との間に区別を提供する。データ抽象化は、表現の具体的な詳細を参照せずにデータに名前を与えることで複雑さを管理する。データは単一の変数として、またはクラスやデータセットなどのデータの集合体として存在する。
  • 3.1.A.3 属性 は、メソッドやコンストラクタの外でクラス内に定義されるデータ抽象化の一種である。インスタンス変数 は、クラスの各インスタンスごとに値が固有である属性である。クラス変数 は、クラスの全インスタンスで共有される属性である。
  • 3.1.A.4 手続的抽象化 はプロセスに名前を与え、メソッドがどのように動作するかではなく何をするのかを知っているだけで使用できるようにする。メソッド分解 を通じて、プログラマーはクラスにより大きな振る舞いをより小さな振る舞いに分解し、それぞれの小さな振る舞いを表すメソッドを作成する。手続的抽象化は、コードを複製する代わりに共通要素を抽出して機能を一般化することがある。これによりコード再利用が可能になり、複雑性の管理に役立つ。
  • 3.1.A.5 パラメータを使用することでプロシージャを一般化でき、異なる入力値や引数を用いてプロシージャを再利用できる。
  • 3.1.A.6 プログラム内で手続的抽象化を使用することで、メソッドの署名とメソッドが何をするかを維持している限り、メソッドユーザーに変更を通知することなく、メソッドの内部(速度向上、効率化、メモリ使用量の削減など)を変更できる。
  • 3.1.A.7 クラスを実装する前に、各クラスの属性と振る舞いを含めた設計に時間を割くことが有益である。この設計は自然言語や図で表現できる。

Source: College Board AP Course and Exam Description · ⁨出典: College Board AP コースおよび試験説明書⁩

English

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.

日本語
進行中のジigsawパズル: クラスとメソッドは大きなプログラム設計におけるモジュール単位のピースです
進行中のジigsawパズル: クラスとメソッドは大きなプログラム設計におけるモジュール単位のピースです

抽象化とは、単純なインターフェースの背後に詳細を隠すことを意味します。Stringを使用する際、それがどのように文字を格納しているかを知る必要はありません。良い設計では問題をクラスに分解し、各クラスが一つの概念について責任を持ちます。このトピックでは、あなた自身がクラスを書くことについて扱います。

プログラムをモジュールとサブモジュールに分解した様子
プログラムをモジュールとサブモジュールに分解する
3.2

The Impact of Program Design · ⁨プログラム設計の影響⁩

Syllabus · ⁨シラバス⁩
English

Learning Objective 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.
日本語

学習目標 3.2.A: コンピューティングシステムの社会的・倫理的 implications を説明する。

  • 3.2.A.1 システム信頼性 とは、指定された条件下で故障なく予期したタスクを遂行できるプログラムの能力を指す。プログラマーは、多様な条件下でプログラム进行测试してシステム信頼性を最大化するよう努めるべきである。
  • 3.2.A.2 プログラムの作成は、社会、経済、文化に影響を与えます。これらの影響には、利益となるものと害をなすものとの両方が含まれます。特定のニーズを満たしたり問題を解決したりするために設計されたプログラムでも、その意図した用途を超えて予期せぬ有害な効果が生じることがあります。
  • 3.2.A.3 プログラムを作成する際、法的問題や知的財産に関する懸念が生じます。プログラマはしばしば、他の人が作成してオープンソースとして公開し無料で利用可能なコードを再利用します。オープンソースとして公開されていないコードを取り込む場合、プログラマはその使用許諾を取得し、統合する前に多くの場合、コードを購入する必要があります。

Source: College Board AP Course and Exam Description · ⁨出典: 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.

日本語

設計上の選択は、コードが正しいか、読みやすいか、再利用可能かどうかに影響します。カプセル化 – データをプライベートに保ち、メソ要通过のみで公開する – はオブジェクトの状態を誤った使用から守り、内部を変更してもクラスのユーザーを破綻させません。 thoughtfulなネーミング、単一目的のメソッド、テストによりバグが減ります。

設計はコード以上の責任も伴います。システム信頼性 – 予期通りタスクを遂行し、失敗なしのプログラム – は、慎重な設計とテストを通じてprogrammableが最大化すべきものです。プログラムは社会、経済、文化に有益かつ有害の両方の現実的な影響を与えます。また、プログラムの作成は法的および知的財産の問題を提起します – programmersはよくオープンソースとして公開され無料で使えるコードを再利用しますが、ライセンスを尊重し、他者の作品をそのまま自分のものとしてコピーするのではなく、出典を示す必要があります。

3.3

The Anatomy of a Class · ⁨クラスの解剖学⁩

Syllabus · ⁨シラバス⁩
English

Learning Objective 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.
日本語

学習目標 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 として指定されたメソッドはクラス内部のみからアクセス可能である。

Source: College Board AP Course and Exam Description · ⁨出典: 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:

日本語

クラスには三つの部分があります:インスタンス変数(フィールド – オブジェクトのデータ)、コンストラクタ(オブジェクトの生成)、そしてメソッド(振る舞い)。フィールドは通常 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
}
青写真: クラスはその型のオブジェクトがどのように構築されるかを定義するテンプレートです
青写真: クラスはその型のオブジェクトがどのように構築されるかを定義するテンプレートです
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. · ⁨クラスは関連するデータ(fields)とメソッドをグループ化します。各オブジェクトには独自のフィールドボックスのセットが割り当てられ、1つに代入しても対象となるオブジェクトのみが変化します。⁩

Vocabulary · ⁨語彙⁩ Train · ⁨練習する⁩
English 日本語
Abstraction/əbˈstrækʃn/ 抽象化
Encapsulation/ɪnˌkæpsjʊˈleɪʃn/ カプセル化
System reliability/ˈsɪstəm rɪˌlaɪəˈbɪlɪti/ システム信頼性
legal and intellectual-property/ˈliːɡl ænd ˌɪntəˈlektʃuːəl ˈprɒpəti/ 法的および知的財産権
open source/ˈəʊpən sɔːs/ オープンソース
instance variables/ˈɪnstəns ˈveərɪəblz/ インスタンス変数
constructor/kənˈstrʌktə/ コンストラクタ
overloading/ˌəʊvəˈləʊdɪŋ/ オーバーロード
accessor (getter)/əkˈsesə/ アクセサ(ゲッター)
3.4

Constructors · ⁨コンストラクタ⁩

Syllabus · ⁨シラバス⁩
English

Learning Objective 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.
日本語

学習目標 3.4.A: クラスのコンストラクタ本体において初期化する対象の属性に対応するインスタンス変数を宣言するコードを作成する。

  • 3.4.A.1 オブジェクトの 状態 は、ある時点におけるその属性およびその値を指し、オブジェクトに属するインスタンス変数によって定義される。これは、オブジェクトとインスタンス変数の間に has-a 関係が成立することを意味する。
  • 3.4.A.2 コンストラクタは、オブジェクトの初期状態を設定するために用いられ、すべてのインスタンス変数に対する初期値を含めるべきである。コンストラクタが呼び出されると、オブジェクトのためにメモリが割り当てられ、関連するオブジェクト参照が返される。コンストラクタのパラメータ(指定されている場合)は、インスタンス変数を初期化するためのデータを提供する。
  • 3.4.A.3 可変オブジェクトがコンストラクタパラメータである場合、インスタンス変数は参照先のオブジェクトのコピーで初期化されるべきである。このようにすることで、インスタンス変数は元のオブジェクトへの参照を持たず、メソッドによる元のオブジェクトの状態の変更を防ぐことができる。
  • 3.4.A.4 コンストラクタが書かれていない場合、Javaは引数なしのコンストラクタを提供し、インスタンス変数は属性のデータ型に応じてデフォルト値に設定される。このコンストラクタを デフォルトコンストラクタ と呼ぶ。
  • 3.4.A.5 int 型の属性のデフォルト値は 0 である。 double 型の属性のデフォルト値は 0.0 である。 boolean 型の属性のデフォルト値は false である。参照型の変数のデフォルト値は null である。

Source: College Board AP Course and Exam Description · ⁨出典: 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 sets defaults.

日本語

コンストラクタはクラスと同じ名前を持ち、返り値の型はありません。new を書いたときに実行され、フィールドを初期化する役割があります。パラメータリストが異なる複数のコンストラクタ(オーバーロード)を持つことができ、引数なしのコンストラクタはデフォルト値を設定します。

3.5

Methods: How to Write Them · ⁨メソッド: 書き方⁩

Syllabus · ⁨シラバス⁩
English

Learning Objective 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.
日本語

学習目標 3.5.A: プリミティブ値を用いてクラス内に書かれたメソッドを通じてオブジェクトの振る舞いを定義するコードを作成し、これらのメソッドを呼び出した結果を判定する。

  • 3.5.A.1 void メソッドは値を返さない。そのヘッダーには、メソッド名の前にキーワード void が含まれる。
  • 3.5.A.2 非voidメソッドは単一の値を返す。そのヘッダーには、キーワード void の代わりに返り値の型が含まれる。
  • 3.5.A.3 非voidメソッドでは、返り値の型と互換性のある返還式が評価され、その値が返される。これを 値による返還 と呼ぶ。
  • 3.5.A.4 return キーワードは、制御の流れをメソッドまたはコンストラクタが呼び出された地点へ戻すために用いられる。return文の後に続くコードは決して実行されない。選択文または反復文内でreturn文を実行すると、该文が停止し、メソッドまたはコンストラクタから退出する。
  • 3.5.A.5 アクセサメソッド は、他のクラスのオブジェクトがインスタンス変数またはクラス変数の値のコピーを取得できるようにするメソッドである。アクセサメソッドは非voidメソッドである。
  • 3.5.A.6 ミューテータ(修飾)メソッド は、インスタンス変数またはクラス変数の値を変更するメソッドである。ミューテータメソッドは多くの場合、voidメソッドである。
  • 3.5.A.7 パラメータを持つメソッドは、そのパラメータを通じて値を受け取り、その値を使用してメソッドのタスクを遂行する。
  • 3.5.A.8 引数がプリミティブ値である場合、パラメータはその値のコピーで初期化される。パラメータへの変更は対応する引数には影響しない。

Source: College Board AP Course and Exam Description · ⁨出典: 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.

日本語

メソッドにはシグネチャ、返り値の型、本体があります。アクセサ(ゲッター) はオブジェクトを変更することなく情報を返します。ミューテータ(セッター) はフィールドを変更します。値を返すメソッドは、すべてのパスで適切な型のreturnを持つ必要があります;voidメソッドは何も返しません。

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. · ⁨メソッドを呼び出すと、その引数を含むフレームがスタックに押し込まれます。returnに到達するとフレームがポップされ、値が呼び出し元に戻ります。⁩

Vocabulary · ⁨語彙⁩ Train · ⁨練習する⁩
English 日本語
mutator (setter)/mjuːˈteɪtə/ ミューテータ(セッター)
static (class) variable/ˈstætɪk ˈveərɪəbl/ 静的(クラス)変数
3.6

Passing and Returning References of an Object · ⁨オブジェクトへの参照の渡還と返却⁩

Syllabus · ⁨シラバス⁩
English

Learning Objective 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.
日本語

学習目標 3.6.A: オブジェクト参照を用いてクラス内に書かれたメソッドを通じてオブジェクトの振る舞いを定義するコードを作成し、これらのメソッドを呼び出した結果を判定する。

  • 3.6.A.1 引数がオブジェクト参照である場合、パラメータはその参照のコピーで初期化されますが、オブジェクト自体の新しい独立したコピーは作成されません。パラメータが可変なオブジェクトを指している場合、メソッドやコンストラクタはこの参照を使ってオブジェクトの状態を変更できます。仕様で必要とされない限り、パラメータとして渡された可変なオブジェクトを修改しないことが良いプログラミングの慣行です。
  • 3.6.A.2 返り値がオブジェクト参照を評価する場合、その参照が返されますが、オブジェクトの新しいコピーに対する参照が返されるわけではありません。
  • 3.6.A.3 パラメータがオブジェクトへの参照を持っている場合、そのパラメータがメソッドを包み込むクラスと同じ型でない限り、メソードはパラメータの private データや private メソッドにアクセスできません。

Source: College Board AP Course and Exam Description · ⁨出典: 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.

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):

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.

日本語
= はオブジェクトそのものをコピーするのではなく参照をコピーします

オブジェクトをメソッドに渡すと、Javaは参照のコピーを取るため、メソッドは同じオブジェクトに対して動作し、そのフィールドへの変更は呼び出し主に visibility されます。(プリミティブは値によってコピーされるため、変更は反映されません。)メソッドはまた、オブジェクトへの参照を返すこともできます。String は不変体であるため、渡すことは安全ですが、可変なオブジェクトを渡すとメソッドが変更できます。

Javaは値渡し:メソッドはコピーを受け取ります。Javaには欠如している真の参照渡しであれば、呼び出し者の変数を再代入できます *Javaは常に値渡し(左):メソッドは参照のコピーを取得する。真の参照渡し(右)– Javaにはない – は、メソッドが呼び出し主自身の変数を再割り当てすることを可能にする。

試験技能: メソッド内でオブジェクトのフィールドを改変すると元の値に影響を与えるが、パラメータの再割り当て(param = new...)は呼び出し主に影響しないことを知っておく。

演習例。 sがStudentであり、得点が50であると仮定して、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 が指すオブジェクトを変更するため、呼び出し主は now 100 を見る。行(2)はメソッド自身の参照のコピーを新しいオブジェクトにポイントさせる – 呼び出し主の s は untouched – 、行(3)はその新しいオブジェクトのみに影響する。呼び出し後、s.getScore() は 100 である:mutationは残ったが、reassignmentは残らなかった。

3.7

Class Variables and Class Methods · ⁨クラス変数とクラスメソッド⁩

Syllabus · ⁨シラバス⁩
English

Learning Objective 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.

Learning Objective 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.
日本語

学習目標 3.7.A: クラスメソッドを通じてクラスの振る舞いを定義するコードを作成する。

  • 3.7.A.1 クラスメソッドは、パラメータ経由でクラスのインスタンスが渡されていない限り、インスタンス変数の値にアクセスしたり変更したり、インスタンスメソッドを呼び出したりすることはできません。
  • 3.7.A.2 クラスメソッドはクラス変数の値にアクセスしたり変更したりでき、他のクラスメソッドを呼び出すことができます。

学習目標 3.7.B: クラスに属するクラス変数を宣言するコードを作成する。

  • 3.7.B.1 クラス変数はクラスに属し、あるクラスのすべてのオブジェクトがそのクラス変数の単一のコピーを共有します。クラス変数は変数名の前に static キーワードが付与されます。
  • 3.7.B.2 public で指定されたクラス変数は、クラスに紐付いているため、クラスのオブジェクトではなく、クラス名とドット演算子を使用してクラス外からアクセスされます。
  • 3.7.B.3 変数が final で宣言された場合、その値は修改できません。

Source: College Board AP Course and Exam Description · ⁨出典: 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().

日本語

*static vs インスタンスフィールド

static(クラス)変数は static でマークされており、クラスの全オブジェクトで共有される – 全体で一つのコピー(例:存在するオブジェクトのカウンター)。staticメソッドはクラスに属し、インスタンスフィールドを直接使うことはできません。クラス名でアクセスする:Student.getCount()。

3.8

Scope and Access · ⁨スコープとアクセス⁩

Syllabus · ⁨シラバス⁩
English

Learning Objective 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.
日本語

学習目標 3.8.A: コード内で変数がどこで使用できるかを説明する。

  • 3.8.A.1 ローカル変数 は、コードブロックのヘッダーまたは本体に宣言された変数です。ローカル変数は、宣言されたブロック内でのみアクセスできます。コンストラクタとメソッドはコードブロックであるため、コンストラクタやメソッドのパラメータもローカル変数とみなされます。これらの変数はコンストラクタやメソッド内でのみ使用でき、public や private に宣言することはできません。
  • 3.8.A.2 インスタンス変数と同じ名前のローカル変数やパラメータが存在する場合、コンストラクタやメソッドの本体では変数名はインスタンス変数ではなくローカル変数を指します。

Source: College Board AP Course and Exam Description · ⁨出典: 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.

日本語

スコープとは、名前が visibility される場所である。メソッド内で宣言されたローカル変数はその中にのみ存在し、パラメータはそのメソッド内にのみ存在し、インスタンス変数はオブジェクト全体で visibility される。アクセス修飾子はクラス間での visibility を制御する:private(このクラスのみ)対 public(どこでも)。ローカル変数は同名のフィールドをシャドウイングする – バグの原因になる。

グローバル変数はどこでも visibility される; ローカル変数はブロック内でのみ visibility される
グローバル変数はどこでも visibility される; ローカル変数はブロック内でのみ visibility される
Vocabulary · ⁨語彙⁩ Train · ⁨練習する⁩
English 日本語
Scope/skəʊp/ スコープ
3.9

The this Keyword · ⁨this キーワード⁩

Syllabus · ⁨シラバス⁩
English

Learning Objective 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.
日本語

学習目標 3.9.A: 自身を参照する式のためのコードを作成し、これらの式の結果を決定する。

  • 3.9.A.1 インスタンスメソッドやコンストラクタ内で、キーワード this は現在のオブジェクトへの参照を持つ特殊な変数として機能します。これは、現在メソッドやコンストラクタが呼び出されているオブジェクトです。
  • 3.9.A.2 キーワード this を使用して、現在のオブジェクトをメソッド呼び出しの引数として渡すことができます。
  • 3.9.A.3 クラスメソッドには this 参照がありません。

Source: College Board AP Course and Exam Description · ⁨出典: 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:

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.

日本語

this は現在のオブジェクトを指します。同じ名前のパラメータと区別したり、同じオブジェクトの他のメソッドを呼び出したりするために使用します:

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

試験対策: コンストラクタやセットメソッドのパラメータがフィールドと同じ名前の場合、this.field = param を必ず書く必要があります——this がなければ、代入は意味のある動作を行いません。

3.9

Exam tips · ⁨試験対策⁩

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 class is a subclass of Object (designing and implementing inheritance is outside the exam's scope).
日本語
  • メソッドとクラスを用いた設計:データをprivate フィールドとしてカプセル化し、公的メソッドを通じて振る舞いを公開する。
  • オブジェクトとそれに対応するクラスの違いを理解し、オブジェクトは値渡しで渡されることを知る——パラメータには参照のコピーが入るため、メソッド内でオブジェクトの状態を変更することはできるが、パラメータへの再割り当ては呼び出し側に影響しない(Javaには参照渡しはない)。
  • アレイとArrayList を安全にトラバースする——サイズはlength と.size() で異なり、ループ中に要素を削除するとインデックスがシフトする。
  • 再帰メソッドをトレースして結果を求める:まず基底ケースを見つけ、次に各再帰呼び出しが返す値まで追跡する(再帰コードの記述は試験範囲外)。
  • 継承に関する用語を理解する——スーパークラス、サブクラス、メソッドのオーバーライド、およびすべてのクラスがObject のサブクラスであること(継承の設計と実装は試験範囲外)。

Interactive lessons on this topic · ⁨このトピックのインタラクティブ授業⁩

Work through it step by step, with instant-check exercises. · ⁨一歩ずつ進め、即時チェック付きの問題で学習します。⁩

Past Papers · ⁨過去問⁩

More topics in AP Computer Science A · ⁨APコンピュータサイエンスA⁩ · ⁨AP Computer Science A · ⁨APコンピュータサイエンスA⁩ の他のトピック⁩

Log in or create account · ⁨ログインまたはアカウント作成⁩

IGCSE, A-Level & AP