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&#91;&#93; args) {
int&#91;&#93; a = {-10,0,20,-1,5};
for(int i=0;i<5;i++) {
System.out.println(a&#91;i&#93; + ":" + sgn(a&#91;i&#93;));
}
}
}
&#91;/java&#93;</p>
<p>上記はmainメソッドでオブジェクト化していない。なので直接メソッドを呼び出すにはstaticメソッドである必要がある。</p>
<p>
class Max1 {
//staticである必要はない
public int max(int a, int b) {
if(a > b){
return a;
}else{
return b;
}
}
}</p>
<p>public class MethodTest1 {</p>
<pre><code>//main_class
public static void main(String[] args) {
    int a=20,b=50;
    Max1 max_obj = new Max1();
    System.out.println(&quot;最大 = &quot; + max_obj.max(a,b));
}</code></pre>
<p>}

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

Java

Posted by bistro