接口中的内部类
2015-12-10 11:37
204 查看
正常情况下,不能字啊接口内部放置任何代码,但嵌套类可以作为接口的一部分。因为你放到接口中的任何类都是自动地是public和static的。
因为类是static的,只是想嵌套类置于接口的命名空间内,这并不违反接口的规则。甚至可以在内部类中实现其外围接口。
eg:
public interface ClassInInterface {
void howdy();
static class Test implements ClassInInterface{
public void howdy(){
System.out.println("Howdy!");
}
public static void main(String[] args) {
new Test().howdy();
}
}
}
result:
Howdy!
public interface ClassInInterface {
void howdy();
class Test implements ClassInInterface{
public void howdy(){
System.out.println("Howdy!");
}
public static void main(String[] args) {
new Test().howdy();
}
}
}
找不到主类
想要创建某些公共代码,使得它们可以被某个接口的所有不同实现所公用,那么使用接口内部的嵌套类会显得很方便。
如果在每一个类中都写一个main()方法,用来测试这个类。这样做有一个缺点,那就是必须带着那些已编译过的额外代码,
如果你认为这是个麻烦,那就可以使用嵌套类放置测试代码。
public class TestBad {
public void f(){
System.out.println("f()");
}
public static class Tester{
public static void main(String[] args) {
TestBad t = new TestBad();
t.f();
}
}
}
因为类是static的,只是想嵌套类置于接口的命名空间内,这并不违反接口的规则。甚至可以在内部类中实现其外围接口。
eg:
public interface ClassInInterface {
void howdy();
static class Test implements ClassInInterface{
public void howdy(){
System.out.println("Howdy!");
}
public static void main(String[] args) {
new Test().howdy();
}
}
}
result:
Howdy!
public interface ClassInInterface {
void howdy();
class Test implements ClassInInterface{
public void howdy(){
System.out.println("Howdy!");
}
public static void main(String[] args) {
new Test().howdy();
}
}
}
找不到主类
想要创建某些公共代码,使得它们可以被某个接口的所有不同实现所公用,那么使用接口内部的嵌套类会显得很方便。
如果在每一个类中都写一个main()方法,用来测试这个类。这样做有一个缺点,那就是必须带着那些已编译过的额外代码,
如果你认为这是个麻烦,那就可以使用嵌套类放置测试代码。
public class TestBad {
public void f(){
System.out.println("f()");
}
public static class Tester{
public static void main(String[] args) {
TestBad t = new TestBad();
t.f();
}
}
}