How to implement nested non-static classes in interfaces?

Having this class

public abstract class Mother{ public class Embryo{ public void ecluse(){ bear(this); } } abstract void bear(Embryo e); } 

I can only create an Embryo instance if I have an instance of Mother:

 new Mother(){...}.new Embryo().ecluse(); 

Question:

  • How to define Mother as an interface?
+7
java interface
source share
1 answer

The Embryo nested class is implicitly static in the interface .

Thus, he does not have access to the practically invokable bear method, which will apply to instances of your Mother interface.

Thus:

  • You declare Mother as an interface , then your Embryo ecluse method cannot actually call bear because it is statically-copied
  • Or you save Mother as an abstract class , but for an Embryo instance (but Embryo requires an instance of Mother (anonymous or child class)) instance-scoped, unless otherwise specified, and can actually call bear )

Standalone Example

 package test; public class Main { public interface MotherI { // this is static! public class Embryo { public void ecluse() { // NOPE, static context, can't access instance context // bear(this); } } // implicitly public abstract void bear(Embryo e); } public abstract class MotherA { public class Embryo { public void ecluse() { // ok, within instance context bear(this); } } public abstract void bear(Embryo e); } // instance initializer of Main { // Idiom for initializing static nested class MotherI.Embryo e = new MotherI.Embryo(); /* * Idiom for initializing instance nested class * Note I also need a new instance of `Main` here, * since I'm in a static context. * Also note anonymous Mother here. */ MotherA.Embryo ee = new MotherA() {public void bear(Embryo e) {/*TODO*/}} .new Embryo(); } public static void main(String[] args) throws Exception { // nothing to do here } } 
+6
source share

All Articles