访问嵌套接口数据变量

时间:2017-06-02 10:00:58

标签: java interface nested

我无法访问此代码的变量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

2 个答案:

答案 0 :(得分: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();

    }
}

答案 1 :(得分:0)

您可以将其编码如下

我已将这些课程分开以供参考

<强> three.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 one

然后您将获得以下输出

 How! i = 2

 What! i = 2

 What! i = 2

在您的问题中我理解的是界面三种方法无法访问界面二的 i 变量,

或者您可以像这样编码

<强> three.java

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

<强> one.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

希望这有助于解决您的问题。