Any class we put inside an interface is automatically public and static. Since the class is static, the nested class is only placed inside the namespace of the interface.
// innerclasses/ClassInInterface.java
// (c)2017 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.
// {java ClassInInterface$Test} // note, cd innerclasses to use this command
public interface ClassInInterface {
void howdy();
class Test implements ClassInInterface {
@Override
public void howdy() {
System.out.println("Howdy!");
}
public static void main(String[] args) {
new Test().howdy();
}
}
}
/* Output:
Howdy!
*/
When we put a main() in every class to act as a test bed for that class. A potential drawback is that our test fixtures are exposed in our shipping product. If this is a problem, we can use a nested class to hold our test code:
// innerclasses/TestBed.java
// (c)2017 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.
// Putting test code in a nested class
// {java TestBed$Tester} // we must escape the $ under Unix/Linux systems
public class TestBed {
public void f() {
System.out.println("f()");
}
public static class Tester {
public static void main(String[] args) {
TestBed t = new TestBed();
t.f();
}
}
}
/* Output:
f()
*/
references:
1. On Java 8 - Bruce Eckel
2. https://github.com/wangbingfeng/OnJava8-Examples/tree/master/innerclasses
3. https://github.com/wangbingfeng/OnJava8-Examples/blob/master/innerclasses/TestBed.java