黑马程序员技术交流社区

标题: 匿名内部类练习 [打印本页]

作者: fmi110    时间: 2015-7-8 18:13
标题: 匿名内部类练习
匿名

  1. [code]
  2. interface Inter  //接口不可以创建对象,因为接口中有抽象方法
  3. {
  4.         void method();//abstract void method();
  5. }

  6. class Test
  7. {
  8.         /*补足代码通过匿名内部类*/
  9.         static Inter function()
  10.         {
  11.                 return new Inter()
  12.                 {
  13.                         public void method()
  14.                         {
  15.                                 System.out.println("method run");
  16.                         }
  17.                 };
  18.         }
  19.        
  20.                                 /*内部类代码实现

  21.                                         static class Inner implements Inter
  22.                                         {
  23.                                                 public void method()
  24.                                                 {
  25.                                                         System.out.println("method run");
  26.                                                 }
  27.                                         }
  28.                                 //        static void function() //InnerClassTest.java:30: 错误: 无法取消引用void
  29.                                 //        {
  30.                                 //                new Inner();
  31.                                 //        }
  32.                                         static Inter function()
  33.                                         {
  34.                                                 return new Inner(); //new Inter错误,抽象类无法实例化
  35.                                         }

  36.                                 */
  37. }

  38. class InnerClassTest
  39. {
  40.         public static void main(String[] args)
  41.         {
  42.                 Test.function().method();//类名调用方法
  43.         }
  44. }
复制代码







欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2