2017-06-02 197 views
1

我不能訪問變量i此代碼:訪問嵌套接口數據變量

interface three{ 
    void how(); 
    interface two{ 
     int i=2; 
     void what(); 
    } 
} 

class one implements three,two{ 

    public void how(){ 
     System.out.println("\nHow! i = " + i); 
     what(); 
    } 

    public void what(){ 
     System.out.println("\nWhat! i = " + i); 
    } 

    public static void main(String args[]){ 
     one a = new one(); 
     a.how(); 
     a.what(); 

    } 
} 

所生成的錯誤是:

one.java:17: error: cannot find symbol 
System.out.println("\nWhat! i = " + i);           
symbol: variable i 
location: class one 
+1

您可以隨時以'two.i'的形式訪問它。無論如何,你的方法似乎在IntelliJ中爲我編譯。而且,這樣的嵌套界面可能會很複雜並且會造成麻煩。 – patrik

回答

0

碼本如下

3。 java

public interface three{ 
    void how(); 
} 

然後編譯爲javac的three.java

two.java後

public interface two{ 
     int i=2; 
     void what(); 
} 

編譯爲javac的two.java

然後

one.java

class one implements two,three{ 
    public void how(){ 
     System.out.println("\nHow! i = " + i); 
    what(); 
    } 

    public void what(){ 
     System.out.println("\nWhat! i = " + i); 
    } 

    public static void main(String args[]){ 
    one a = new one(); 
    a.how(); 
    a.what(); 
    } 
} 

然後編譯如下

的javac one.java

之後運行它

java的一個

那麼你會得到下面的輸出

How! i = 2 

What! i = 2 

What! i = 2 

在你的問題,我的理解是接口三種方法都無法訪問該接口二的變量,

或者你可以這樣編碼

three.java

public interface three{ 
    void how(); 
    interface two{ 
     int i=2; 
     void what(); 
    } 
} 

之一。java的

class one implements three.two{ 
    public void how(){ 
     System.out.println("\nHow! i = " + i); 
     what(); 
    } 

    public void what(){ 
     System.out.println("\nWhat! i = " + i); 
    } 

    public static void main(String args[]){ 
     three.two a = new one(); 
     a.what(); 
     one b = new one();//created this to call the how() method in one.java 
     b.how(); 
    } 
} 

輸出如下

What! i = 2 

How! i = 2 

What! i = 2 

希望這將有助於解決您的問題。

1

您應該創建外部接口,以便其他類可以訪問它。

interface three { 
    void how(); 
} 

interface two { 
    int i = 2; 

    void what(); 
} 

public class one implements three, two { 

    public void how() { 
     System.out.println("\nHow! i = " + i); 
     what(); 
    } 

    public void what() { 
     System.out.println("\nWhat! i = " + i); 
    } 

    public static void main(String args[]) { 
     one a = new one(); 
     a.how(); 
     a.what(); 

    } 
}