1

I am have an interface with an inner class. Now the question is, why cannot I access the functions defined in the outer interface in a similar way to how methods are accessed in outer classes? I thought things should just work smoothly as this inner class would only be instantiated after a class, implementing the outer interface, being instantiated. Anyways the error I got was "No enclosing instance of the type OterInterface is accessible in scope"

public interface OterInterface {

    public void someFunction1() ;
    public void someFunction2() ;


    public class Innerclass{
        public String value1;
        public String value2;

        public String getValue1() {
            OterInterface.this.someFunction1();         
            return value1;
          }
      }     
}
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
Shaki
  • 349
  • 3
  • 8

2 Answers2

1

In this case you can use anonymous inner class. As you can't instantiate any interface it is impossible to access their methods. Interfaces are incomplete classes with unimplemented methods. In order to instantiate it you have to provide the implementation for its methods.

 public interface OterInterface {

    public void someFunction1() ;
    public void someFunction2() ;


    public class Innerclass{
        public String value1;
        public String value2;

        public String getValue1() {
            new OterInterface(){
                public void someFunction1() {
                    System.out.println("someFunction1()");
                }
                public void someFunction2() {
                    System.out.println("someFunction2()");
                }
            }.someFunction1();
            return value1;
          }
      }     
}
Rockstar
  • 2,228
  • 3
  • 20
  • 39
1

Consider what instance of OterInterface you are attempting to perform 'someFunction' on. 'this' refers to the current object - OterInterface is an interface and as such does not have a current object.

So you can't reference OterInterface.this from there, as the compiler has no idea which object instance you are referring to!

Community
  • 1
  • 1
Kieran
  • 343
  • 2
  • 10