0

I was trying to develop an interface and that interface will contain static class

class C1 {

    static interface I // A static interface or class can contain static members.Static members can be
    //accessed without instantiating the particular class
    {

        static class C2 {
        }
    }

    public static void main(String a[]) {
        C1.I.C2 ob1 = new C1.I.C2();
        System.out.println("object created");
    }
}

But my query is that can interface contain classes which are not static and if yes , then how their object would be created , please advise. Thanks

assylias
  • 321,522
  • 82
  • 660
  • 783
dghtr
  • 561
  • 3
  • 6
  • 20

1 Answers1

3

Can an interface contain classes?

Yes. For example, in

interface Widget {
  static class Factory {
    static Widget create() { return new Widget() {}; }
  }
}

the inner class can be accessed as

Widget w = Widget.Factory.create();

so to refer to the inner class you can just use the interface name then a dot then the inner class name

import my.pkg.MyInterface;

...

  MyInterface.InnerClass ic = new MyInterface.InnerClass();
Mike Samuel
  • 118,113
  • 30
  • 216
  • 245