「Java8」クラスのstaticメソッドを使用する方法
環境
JavaSE1.8
Eclipse 2019-12
書式
class クラス名{
static データ戻り値の型 メソッド名() {
static データの型 変数名 =値
}
}
構文
クラス名.staticメソッド名
クラス名.static変数名
staticメソッドは、クラスをインスタンス化せずにメソッドを使用できます。
メソッドの前にstatic修飾子をつけます。
クラスをインスタンス化していませんが値が表示されます
使用例
package com.arkgame.study;
//クラスCityの定義
class City {
// static変数の定義
static String target = "study skill become smart";
// staticメソッドの定義
static void funA() {
System.out.println("東京tokyo");
}
}
public class StaticDemo {
public static void main(String[] args) {
System.out.println("クラスのstaticメソッドを呼び出します");
City.funA();
System.out.println("----------------");
System.out.println("クラスのstatic変数を呼び出します");
System.out.println(City.target);
}
}
実行結果
クラスのstaticメソッドを呼び出します 東京tokyo ---------------- クラスのstatic変数を呼び出します study skill become smart