作者qrtt1 (隐者)
看板java
标题Re: [问题] static method
时间Mon Jun 19 18:04:24 2006
※ 引述《hpeter (hpeter)》之铭言:
: ※ 引述《justinC (无)》之铭言:
: : public class test {
: : public static void main(String args[]) {
: : System.out.print(more(2,4,4,4));
: : }
: : public static int more(int... num)
: : {
: : int total=0;
: : for(int a:num)
: : total+=a;
: : return total;
: : }
: : }
: : 为什麽在class test底下
: : more method一定要加static 才能给过?
: : 而其他class则不需用呢?
: 小弟觉得 因为被 static function 用到的东西
: 一定要有static 之修饰
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Cannot make a static reference to the non-static method more(int[]) from
the type test
at test.main(test.java:3)
=============================================================================
俺在初学java时也是和您一样的想法,因为这样的错误讯息。我在被用到的method field
都加了static,後来发现原来只要产生了instance就能正确地呼叫。
所以,我们有权选择static or non-static,至於如何选择简单的判断是
1. 以field而言
你要所有instance共同一个变数时, 那就static。
2. 以method而言
有static时会想想, 这功能到底属不属於该class, 如果不属於乾脆丢到杂项的class
如果属於那只好免强放一下呗>"<
--
※ 发信站: 批踢踢实业坊(ptt.cc)
◆ From: 163.26.34.105