6

The java compiler allows me write a Class definition inside an Interface . Are there any specific uses of this ?

interface ClassInterface {

  void returnSomething();
  int x = 10;

  class SomeClass {
    private int y;

    private void classDoingSomething() {         
    }
  }
}

Please explain .

AllTooSir
  • 47,910
  • 16
  • 124
  • 159
  • 1
    possible duplicate: http://stackoverflow.com/questions/594789/practical-side-of-the-ability-to-define-a-class-within-an-interface-in-java – Korhan Ozturk Feb 01 '12 at 15:16
  • 1
    possible duplicate of [inner class within Interface](http://stackoverflow.com/questions/2400828/inner-class-within-interface) – aioobe Feb 01 '12 at 15:16

2 Answers2

4

The uses are the same that a class nested in another class: it allows scoping the class to the interface. You could imagine something like this:

public interface Switch {

    public enum Status {
        ON, OFF;
    }

    void doSwitch();
    Status getStatus();
}

It avoids defining a top-level class named SwitchStatus (because Status could be a too generic name).

JB Nizet
  • 657,433
  • 87
  • 1,179
  • 1,226
2

You would use it to tightly bind a certain type to an interface. Read This page for further information and an example of defining a class inside an interface.

Korhan Ozturk
  • 10,880
  • 6
  • 34
  • 47
  • Indeed.. Here I am using it to embed the [Null object](https://en.wikipedia.org/wiki/Null_Object_pattern) implementation of an interface, so I don't need to create a class file for it. – Campa Jul 03 '15 at 07:20