Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement nested non-static classes in interfaces?

Tags:

java

interface

Having this class

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

i can create a Instance of Embryo only if i have a instance of Mother:

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

Question:

  • How to define Mother as an interface?
like image 296
Grim Avatar asked Jan 28 '16 15:01

Grim


1 Answers

The nested class Embryo is implicitly static in an interface.

As such, it does not have access to the virtually invokable method bear, which would pertain to instances of your Mother interface.

Therefore:

  • Either you declare Mother as interface, then your Embryo's ecluse method cannot virtually invoke bear because it's statically-scoped
  • Or, you keep Mother as an abstract class, but require an instance of a Mother (anonymous or a child class' instance) in order to get an instance of Embryo (but Embryo is instance-scoped unless specified otherwise, and can invoke bear virtually)

Self-contained 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
    }
}
like image 166
Mena Avatar answered Oct 19 '22 12:10

Mena