2012-07-31 35 views
2
public class InterfaceTest { 
    interface InterfaceA { 
     int len = 1 ; 
     void output(); 
    } 

    interface InterfaceB { 
      int len = 2 ; 
      void output(); 
    } 

    interface InterfaceSub extends InterfaceA, InterfaceB {   } 

    public class Xyz implements InterfaceSub { 

     public void output() { 
      System.out.println("output in class Xyz."); 
     } 

      public void outputLen(int type) { 
       switch (type) { 
         case InterfaceA.len: 
          System.out.println("len of InterfaceA=." +type); 
           break ; 
         case InterfaceB.len: 
          System.out.println("len of InterfaceB=." +type); 
           break ; 
      } 
     } 
    } 

    public static void main(String[] args) { 
      Xyz xyz = new Xyz(); 
      xyz.output(); 
      xyz.outputLen(1); 
    } 
} 

嗨, 我想學習Java的接口和多繼承概念。 我發現上面的代碼並嘗試編譯它,但會發生下面的錯誤。我不知道如何使代碼工作,誰可以提供幫助? 謝謝!如何在Java中解決這個「非靜態變量」問題?

test$ javac InterfaceTest.java 
InterfaceTest.java:33: error: non-static variable this cannot be referenced from a static context 
      Xyz xyz = new Xyz(); 
        ^
1 error 

回答

4

這是因爲,非靜態內部類不能在靜態方法中被實例化,因爲它不具有封閉類一起工作的一個實例。

如果您定義的Xyz爲靜態內部類它應該工作:

public static class Xyz implements InterfaceSub { 
    .... 
} 

或者,也可以在外圍類的一個實例中創建的Xyz - 這裏沒有必要的,但此將需要如果的Xyz需要訪問封閉類的一些成員變量。

2

您需要在InterfaceTest之外定義Xyz(或更改其可見性)。

3

取代

Xyz xyz = new Xyz(); 

Xyz xyz = new InterfaceTest().new Xyz(); 
+0

非常有用的答案! – 2012-07-31 05:14:33

相關問題