黑马程序员技术交流社区

标题: 毕老师给出的一个很不错的问题,大家能不能帮解答一下? [打印本页]

作者: 张慈瑞    时间: 2014-7-11 20:34
标题: 毕老师给出的一个很不错的问题,大家能不能帮解答一下?
interface Inter
{
        void method();
}
class Test
{
        //补足代码。通过匿名内部类。
}

class InnerClassTest
{
        public static void main(String[] args)
        {
                Test.function().method();
        }
}
作者: hejinzhong    时间: 2014-7-11 21:02
本帖最后由 hejinzhong 于 2014-7-11 21:17 编辑

interface Inter // 定义了一个接口Inter
{
        void method();
}
class Test
{
        public static Inter function
        {
                return new Inter()
                {
                        这里自己覆写父类中method
                };
        }
}

class InnerClassTest
{
        public static void main(String[] args)
        {
                Test.function().method();
        }
}

分析:在主函数中(Test.function().method();)这句话可以看出,method()方法被调用,而method存在与Inter接口中,所以要使用该方法,必须建立他的子类才可以调用。所以Test.function()的运行结果是个Inter子类类型的类类型数据,而且直接通过Test类名调用了Test内部的function函数,所以function函数是static。
这样的话就可以写出:

class Test
{
        static Inter的子类名 function()
        {
                return  new inter的子类;//因为接口不能直接创建对象,只能有子类实现后才可以.
        }
}

因为这里InnerClassTest 类的主函数只调用一次method,所以可以通过匿名内部类解决,简化代码.
怎么创建匿名内部类,你看看前面概念视频和格式就OK

作者: 玉遥    时间: 2014-7-11 21:04

  1. <P>interface Inter {
  2. void method();
  3. }</P>
  4. <P>class Test {
  5. public static Inter function() {
  6.   return new Inter() {
  7.    public void method() {
  8.     System.out.println("匿名内部类");
  9.    }
  10.   };
  11. }
  12. }</P>
  13. <P>class InnerClassTest {
  14. public static void main(String[] args) {
  15.   Test.function().method();
  16.   // 类名直接调用,function是静态修饰的,而其又调用了接口中的method方法,说明function返回的是一个
  17.   // 接口的子实现类的对象,这里只能用匿名内部类实现方法。
  18. }
  19. }</P>
复制代码


作者: 215041631    时间: 2014-7-11 21:07
package niming;

class  UnName
{
        public static void main(String[] args)
        {
                   Test.function().method();
        }
}

interface Inter
{
        void method();
}
class Test
{
   static Inter function()
        {
                return new Inter()
                {
                        public void method()
                        {
                                System.out.print("Inner");
                        }
                };
        }
}

作者: EarlyHeart    时间: 2014-7-11 21:14
  1. interface Inter {
  2.         void method();
  3. }

  4. class Test {
  5.         public static Inter function() {
  6.                 return new Inter() {                       
  7.                         public void method() {
  8.                                
  9.                         }
  10.                 };
  11.         }
  12. }

  13. class InnerClassTest {
  14.         public static void main(String[] args) {
  15.                 Test.function().method();
  16.         }
  17. }
复制代码





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