標籤:
1.static 關鍵字
- 修飾的成員被所有對象共用(包括成員變數和方法)。
- 修飾的成員優先於對象存在。
- 儲存於方法區(共用資料區)的靜態區中。
- 靜態方法只能訪問靜態成員。
- 靜態方法中不可以使用this或super關鍵字。
- 主函數是static,只能調用static方法。
- 靜態代碼塊隨著類的載入而運行(只執行一次)。用於給類進行初始化。
Q:
I have the following code:
1: class Hello {
2: class Thing {
3: public int size;
4:
5: Thing() {
6: size = 0;
7: }
8: }
9:
10: public static void main(String[] args) {
11: Thing thing1 = new Thing();
12: System.out.println("Hello, World!");
13: }
14: }
it refuses to compile. I get No enclosing instance of type Hello is accessible." at the line that creates a new Thing.
A:
You‘ve declared the class Thing as a non-static inner class. That means it must be associated with an instance of the Hello class.
In your code, you‘re trying to create an instance of Thing from a static context. That is what the compiler is complaining about.
There are a few possible solutions. Which solution to use depends on what you want to achieve.
-
Change Thing to be a static nested class.
1: static class Thing
-
Create an instance of Hello, then create an instance of Thing.
1: public static void main(String[] args)
2: {
3: Hello h = new Hello();
4: Thing thing1 = h.new Thing(); // hope this syntax is right, typing on the fly :P
5: }
-
Move Thing out of the Hello class.
No enclosing instance of type Hello is accessible