このページには最新のブラウザ(SharedArrayBuffer対応)が必要です。Chrome、Edge、Firefox、Safariを最新バージョンに更新してください。
オリジナルタイプを作成する
- これまでに
StringやMathなど、Javaが用意したクラスを使用してきました。 - 次は独自のクラスを書きます。クラスとはオブジェクトのための設計図です。
- オブジェクトはデータ(自身の値)とメソッド(自身が行えること)を持ちます。
インスタンス変数
- 各オブジェクトが保持するデータはインスタンス変数(フィールドとも呼ばれる)に格納されます。
- クラス内で宣言しますが、どのメソッドの外側で行います。
- 各オブジェクトはこれらの変数の独自のコピーを持ちます。
- 各フィールドの前に
privateを記述する。これによりクラス自身のメソッドのみがアクセスできる。AP答案がこれを採用する理由は、Lesson 7で説明されている。
English
public class Dog {
private String name; // instance variable
private int age; // instance variable
}
コンストラクタ
- コンストラクタは新しいオブジェクトを初期化します。
newを記述したときに実行されます。 - クラスと同じ名前を持ち、返り値の型はありません(
voidを含む場合でも)。 - このオブジェクト自身の变量を指すために
thisという言葉を使います。
English
public class Dog {
private String name;
private int age;
// Constructor: runs when we make a new Dog
public Dog(String name, int age) {
this.name = name; // this.name is the field; name is the parameter
this.age = age;
}
}
インスタンスメソッド
- インスタンスメソッドはオブジェクトが行う動作です。
- オブジェクト自身のインスタンス変数を読み取り、変更できます。
- オブジェクトに対してドットを使って呼び出します:
myDog.speak()。
English
public class Dog {
private String name;
private int age;
public Dog(String name, int age) {
this.name = name;
this.age = age;
}
// Instance method: returns a sentence about this dog
public String describe() {
return this.name + " is " + this.age;
}
}
オブジェクトの作成と使用
new ClassName(...)を使ってオブジェクトを作成します。これによりコンストラクタが呼び出されます。- クラス名と同じ型を持つ変数に格納します。
- その後、ドットを使ってそのメソッドを呼び出します。
English
public class Main {
public static void main(String[] args) {
Dog d = new Dog("Rex", 4);
System.out.println(d.describe()); // Rex is 4
}
}
class Dog {
private String name;
private int age;
public Dog(String name, int age) {
this.name = name;
this.age = age;
}
public String describe() {
return this.name + " is " + this.age;
}
}
なぜ this なのか?
- パラメータとフィールドは同じ名前を持つことができます(例:
name)。 - コンストラクタ内では、
nameはパラメータを意味し、this.nameはフィールドを意味します。 thisは常にメソッドが呼び出されたオブジェクトを指します。
よくあるミス
- コンストラクタには戻り値の型がなく、クラス名と一致します。
- 同名のパラメータとフィールドを区別するために
this.fieldを使います。
あなたも試してみよう
- 各タスクには、TODO が含まれたクラスの骨子が与えられます。コンパイルして動作するように埋めてください。
- 隠された Harness があなたのオブジェクトを作成し、結果をチェックします。
- Check answerを使用して提供されたテストでコードをコンパイルし、結果を確認してください。スタートファイルに表示されているクラスとメソッドのインターフェースを維持してください。
難易度 2/5 · 140 コイン + 今日初回達成時の小ボーナス
Complete the Counter class. It has an int 場として扱う count that starts at 0. increment() adds 1 to it. getCount() returns the current value.
実行ボタンをクリックして出力を確認してください。
難易度 2/5 · 140 コイン + 今日初回達成時の小ボーナス
Complete the Rectangle class. The constructor takes width w and height h and stores them. area() returns width times height. perimeter() returns 2 times (width plus height).
実行ボタンをクリックして出力を確認してください。
難易度 2/5 · 140 コイン + 今日初回達成時の小ボーナス
Complete the Greeter class. The constructor takes a String name and stores it in the field name. greet() returns the text Hello, followed by the name and a ! (for "Ana" it returns Hello, Ana!).
実行ボタンをクリックして出力を確認してください。