≪Java≫ this() コンストラクタの呼び出し
this()を使うと、他のコンストラクタを呼び出すことによって、簡潔に記載できる。
≪this()≫を使わない場合
public class Music {
String title;
String artist;
int price;
//一旦全て空の値や未設定の値で初期化したいコンストラクタ
public Music(){
this.title = “”; // ← null を “”(空白)で初期化
this.artist = “”; // ← null を “”(空白) で初期化
this.price = -1; // ← 0 を -1で初期化
}
//titleとsrtistは引数で、priceは未設定の値で初期化したいコンストラクタ
public Music(String title, String artist){
this.title = title; // ← 引数を代入
this.artist = artist; // ← 引数を代入
this.price = -1; // ← 0 を -1で初期化
}
//全て引数で初期化するコンストラクタ
public Music(String title, String artist, int price){
this.title = title; // ← 引数を代入
this.artist = artist; // ← 引数を代入
this.price = price; // ← 引数を代入
}
≪this()≫を使う場合
public class Music {
String title;
String artist;
int price;
//① 一旦全て空の値や未設定の値で初期化したいコンストラクタ
public Music(){
this(“”, “”, -1) // ← ③のコンストラクタを呼び出して、””や-1で初期化
}
↑ 記述が簡潔化されている。
//② titleとsrtistは引数で、priceは未設定の値で初期化したいコンストラクタ
public Music(String title, String artist){
this(title, artist, -1) // ← ③のコンストラクタを呼び出して、引数や-1で初期化
}
↑ 記述が簡潔化されている。
//③ 全て引数で初期化するコンストラクタ
public Music(String title, String artist, int price){
this.title = title; // ← 引数を代入
this.artist = artist; // ← 引数を代入
this.price = price; // ← 引数を代入
}
【this()を書くときの注意点】
以下の2点に注意しないと、コンパイルエラーになる。
・this()は、コンストラクタの最初の行に書く。(2行目以降に書くとコンパイルエラー)
・メソッドでthis()は使わない。(使うとコンパイルエラーになる)