Java - 两点简单解释static

static:do not need instantiate.

1. static无论是加在member variable还是member method之前,就意味着要访问/调用这个member variable/member method的方法只能使用 <className>.<variableName> 或者 <className>.<methodName>。 而不是像其他member variable/member method被访问前需要先create one object/an instance,然后用这个object name去访问这个class里面的member variable/member method。

[ 即两种访问方法完全不同 ]

2. 在class implementation里面,带有static的method内部也不可以有任何non-static variable or method。反之却可以,即普通的non-static method里面可以有static variable/method。

[ static method限制要比non-static method限制多 ]

 

所以根据以上两条,下面这个例子里面有几处错误。

错误1. line 6 (a non-static method is not allowed in a static method)

错误2. line 8 (a non-static variable is not allowed in a static method)

错误3. line 18 (原因同错误2.)

 1 public class StaticFunSample {
 2     public static final int TARGET_NUM_HATS = 10;
 3     private static int countNumMade = 0;
 4     private int favNum = 0;
 5     public static void main(String[] args) {
 6         changeFavNum(42);
 7         displayInfo();
 8         favNum = 10;
 9         countNumMade = 9;
10     }
11     private void changeFavNum(int i) {
12         favNum = TARGET_NUM_HATS + i;
13         displayInfo();
14     }
15     private static void displayInfo() {
16         System.out.println("TARGET_NUM_HATTS: " + TARGET_NUM_HATS);
17         System.out.println("countNumMade: " + countNumMade);
18         System.out.println("favNum: " + favNum);
19     }
20 }

 

posted @ 2021-09-14 11:35  收割稻谷一堆  阅读(32)  评论(0编辑  收藏  举报