Warning: Trying to access array offset on value of type bool in /home/web13c/bistro.site/public_html/wp-content/themes/luxeritas/inc/json-ld.php on line 120

staticメソッド

static method
インスタンスを作らずに呼び出すことが出来る。

public class Dr11 {
    //オブジェクト化して使わないのでstaticの必要がある
    public static String sgn(int a){
        if(a>0){
            return "正";
        }else if(a<0){
            return "負";
        }else{
            return "ゼロ";
        }
    }
    public static void main(String[] args) {
        int[] a = {-10,0,20,-1,5};
        for(int i=0;i<5;i++) {
            System.out.println(a[i] + ":" + sgn(a[i]));
        }
    }
}

上記はmainメソッドでオブジェクト化していない。なので直接メソッドを呼び出すにはstaticメソッドである必要がある。

class Max1 {
    //staticである必要はない
    public int max(int a, int b) {
        if(a > b){
            return a;
        }else{
            return b;
        }
    }
}
public class MethodTest1 {
    //main_class
    public static void main(String[] args) {
        int a=20,b=50;
        Max1 max_obj = new Max1();
        System.out.println("最大 = " + max_obj.max(a,b));
    }
}

オブジェクト化して使う場合はstaticメソッドである必要はない。

Java

Posted by bistro