4
I was reading about JsInterop
and I come across an example of code:
package com.example;
@JsType
public class Bar {
@JsFunction
public interface Foo {
int exec(int x);
}
public static int action1(Foo foo) {
return foo.exec(40);
}
public static Foo action2() {
return (x) -> x + 2;
}
}
The question has nothing to do with
JsInterop
, was just where I took the example
Note that here, Foo
is a nested interface within class Bar
. Different than what I’m used to nested classes, Foo
is not marked as static.
I know that if the nested class is not declared static, as for example:
package com.example;
public class Marm {
public class Ota {
}
}
every instance of the class Ota
has a reference to Marm.this
, passed as implicit argument to your constructor, and you can then access the private fields and methods of the class that encapsulates it:
package com.example;
public class Marm {
public class Ota {
@Override
public String toString() {
return "" + Marm.this.n;
}
}
private int n;
public Marm(int n) {
this.n = n;
}
public static void main(String... args) {
Ota a;
// se eu fizesse: a = new Ota();
// teria este erro: No enclosing instance of type Marm is accessible. Must qualify the allocation with an enclosing instance of type Marm (e.g. x.new A() where x is an instance of Marm).
a = new Marm(5).new Ota();
System.out.println(a); // imprime 5
}
}
However, I have a question: a nested interface has the same effect if it were "static"? And, with Java 8 allowing methods default
in interfaces, the nested interfaces are unrelated to the Marm.this
and could not refer to it?
And, taking advantage, and as for the private and static methods of the class that enclosed it, the methods default
could have access to them?
A nested interface is
static
for default: https://docs.oracle.com/javase/specs/jls/se8/html/jls-8.html#jls-8.5.1– hkotsubo
@hkotsubo, reply by RTFM, I liked it. If I didn’t have duplication (I don’t think so), I think it’s worth an answer, however brief it is
– Jefferson Quesado