staticインポートとは
本来、staticなフィールドやメソッドを使用する場合、
「クラス名.フィールド名」「クラス名.メソッド名」という書式で記述する必要がありますが、
これを「フィールド名」「メソッド名」のみで記述できるようにするための宣言が
staticインポートです。
staticインポートの書式
staticインポートをする場合、以下のような書式でインポート宣言を行います。
「import static パッケージ名.クラス名.フィールド名」
import static jp.co.xxx.Fuga.field;
「 import static パッケージ名.クラス名.メソッド名 」
import static jp.co.xxx.Fuga.method;
※メソッド呼出ではなく、メソッド名を指定するので「()」は不要
staticインポートを使用した場合
①「フィールド名のみ」の書式でフィールドを扱うことができます。
②「メソッド名のみ」の書式でメソッド呼出することができます。
package jp.co.xxx; public class Fuga(){ public static String field= "Fuga_field"; public static void method(){} }
import static jp.co.xxx.Fuga.field; import static jp.co.xxx.Fuga.method; ←メソッド名なので「()」は不要 public class Hoge(){ public static void main(String[] args){ System.out.println(field); ←フィールド名のみで使用可能 method(); ←メソッド名のみでのメソッド呼出が可能 } }
staticインポートを使用しない場合
staticインポートを指定しない場合、
①「クラス名.フィールド名」の書式でフィールドを扱う必要があります。
②「クラス名.メソッド名」の書式でメソッドを呼出す必要があります。
package jp.co.xxx; public class Fuga(){ public static String field= "Fuga_field"; public static void method(){} }
import jp.co.xxx.Fuga; public class Hoge(){ public static void main(String[] args){ System.out.println(Fuga.field); ←「クラス名.フィールド名」でフィールド使用 Fuga.method(); ←「クラス名.メソッド名」でのメソッド呼出 } }
staticインポート時に同名のフィールド、メソッドが存在した場合
staticインポート時に同名のフィールド、メソッドが存在した場合 は、
処理実行クラスからみて、一番近いのフィールド、メソッドが採用されます。
例えば、Fugaクラスのフィールド、メソッドを、Hogeクラスでstaticインポートした場合
package jp.co.xxx; class Fuga { public static String field = "Fuga-field"; public static String method() { return "Fuga-method"; } }
package jp.co.xxx; import static jp.co.xxx.Fuga.field; ←staticインポート ⇒ 無視される import static jp.co.xxx.Fuga.method; ←staticインポート ⇒ 無視される public class Hoge { public static String field = "Hoge-field"; ←同名のフィールド public static String method() { ←同名のメソッド return "Hoge-method"; } public static void main(String[] args) { System.out.println(field); System.out.println(method()); } }
実行結果
Hoge-field
Hoge-method
上記の場合、インポートを行ったHogeクラスに、インポートされたフィールドとメソッドと同名のものがあるので、インポートは無視され、Hogeクラスで定義されたものが採用されます。
では、以下の場合だと、どうなるでしょう。
package jp.co.xxx; class Piyo { public static String field = "Piyo-field"; public static String method() { return "Piyo-method"; } }
package jp.co.xxx; //Piyoクラスを継承 class Fuga extends Piyo{ //Piyoクラスと同名のフィールド、メソッドを定義 public static String field = "Fuga-field"; public static String method() { return "Fuga-method"; } }
package jp.co.xxx;
import static jp.co.xxx.Fuga.field; ←staticインポート
public class Hoge {
public static void main(String[] args) {
System.out.println(field);
System.out.println(method());
}
}
実行結果
Fuga-field
Fuga-method
上記の場合、Hogeクラスから見て一番近いクラスはFugaクラス、その次にPiyoクラスとなっており、参照しているフィールド、メソッドは 一番近いクラスであるFugaクラス のものとなっています。
結論
staticインポートした場合、同名のフィールドやメソッドがあった場合は、実行クラスからみて、一番近いのフィールド、メソッドが採用される。ということになります。
また、インポートしたクラスに、インポートされたフィールド、メソッドと同名のものがあった場合、そのインポートは無視されることになります。
注意点
※書式に注意
書式は「static import …」ではなく、「import static …」です。
コメント
[…] 前回、『staticインポートの書式』にて、staticインポートで同名のフィールド、メソッドがあった場合の動きについて触れましたが、今回はコンパイルエラーになるパターンについて紹介したいと思います。 […]