匿名
- [code]
- interface Inter //接口不可以创建对象,因为接口中有抽象方法
- {
- void method();//abstract void method();
- }
- class Test
- {
- /*补足代码通过匿名内部类*/
- static Inter function()
- {
- return new Inter()
- {
- public void method()
- {
- System.out.println("method run");
- }
- };
- }
-
- /*内部类代码实现
- static class Inner implements Inter
- {
- public void method()
- {
- System.out.println("method run");
- }
- }
- // static void function() //InnerClassTest.java:30: 错误: 无法取消引用void
- // {
- // new Inner();
- // }
- static Inter function()
- {
- return new Inner(); //new Inter错误,抽象类无法实例化
- }
- */
- }
- class InnerClassTest
- {
- public static void main(String[] args)
- {
- Test.function().method();//类名调用方法
- }
- }
复制代码
|
|