2012-08-06 65 views
20

我開發一個Android應用程序,但已經打了一下磚牆,我不斷收到錯誤:非法修改錯誤靜態類

Illegal modifier for the class FavsPopupFragment; only public, abstract & final are permitted 

這件事發生之後this answer另一個SO問題之後。下面是我的代碼:

package com.package.name; 

/* Imports were here */ 

public static class FavsPopupFragment extends SherlockDialogFragment { 

    static FavsPopupFragment newInstance() { 
     FavsPopupFragment frag = new FavsPopupFragment(); 
     return frag; 
    } 
} 

錯誤出現在類名上。我不明白爲什麼這不會工作,請幫助。謝謝。

+1

在這種情況下,您必須確保或強制自己將'FavsPopupFragment'放在另一個類中。 – 2012-08-06 16:04:32

+0

對我來說,我在看這個問題的原因是我來自C#/ .Net,並且在那裏你可以有靜態的頂級類。雖然事實證明「靜態」是指兩種技術中的兩種不同的東西。 – RenniePet 2014-09-24 21:54:05

回答

38

不能創建一個頂級靜態類;這正是編譯器試圖告訴你的。也有看答案here爲什麼是這種情況。要點是:

What the static boils down to is that an instance of the class can stand on its own. Or, the other way around: a non-static inner class (= instance inner class) cannot exist without an instance of the outer class. Since a top-level class does not have an outer class, it can't be anything but static.

Because all top-level classes are static, having the static keyword in a top-level class definition is pointless.

1

卸下類定義靜態的。只有嵌套classes可以是靜態的。

for the class FavsPopupFragment; only public, abstract & final are permitted

1

我不認爲你可以使用new關鍵字創建一個靜態類的實例。無論如何,這是一個片段,所以它可能不應該是靜態的。

1

你不能使用static修改爲頂級類,雖然有可以嵌套可與static關鍵字修飾類。

在這種情況下,要麼你需要刪除static修飾符,或者確保這個類嵌套到另一個頂層類。

額外的信息

There's no such thing as a static class. The static modifier in this case (static nested) says that the nested class is a static member of the outer class. That means it can be accessed, as with other static members, without having an instance of the outer class.

Just as a static method does not have access to the instance variables and nonstatic methods of the class, a static nested class does not have access to the instance variables and nonstatic methods of the outer class

1

1.static不能被在Package level.

2.static採用的是類級別內可能的。

3.但是你仍然可以使用靜態的一類,當類是inner class,即。 (static inner class),俗稱頂層類。

3

由於以前的答案說,你不能使用在頂級類的static關鍵字。但我想知道,你爲什麼要它是靜態的?

讓我告訴你一個靜態/非靜態內部類是如何在示例中使用:

public class A 
{ 
    public class B{} 

    public static class C{} 

    public static void foo() 
    { 
     B b = new B(); //incorrect 

     A a = new A(); 
     A.B b = a.new B(); //correct 

     C c = new C(); //correct 
    } 
    public void bar() 
    { 
     B b = new B(); 
     C c = new C(); // both are correct 
    } 
} 

而且從一個完全不同的類:

public class D 
{ 
    public void foo() 
    { 
     A.B b = new A.B() //incorrect 

     A a = new A() 
     A.B b = a.new B() //correct 

     A.C c = new A.C() //correct 
    } 
} 
1
  • static可以使用在班級內部。頂級不能爲static,如前所述,只允許使用public,abstract & final

  • static主要用於方法和變量的類級別內部。

1

頂級類從定義上講已經是頂級的了,所以沒有必要聲明它是靜態的;這樣做是錯誤的。編譯器將檢測並報告此錯誤。

相關問題