访问嵌套接口数据变量



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

您应该在外部创建接口,以便其他类可以访问它。

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();
    }
}

您可以按照以下

进行编码

我已经将您的参考的类分开

three.java

 public interface three{
   void how();
 }

然后将其编译为 Javac Trix.java

之后

二.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 varible,

,或者您可以像这样的代码

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

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

最新更新