黑马程序员技术交流社区

标题: 匿名内部类的返回值问题,求救,谢谢! [打印本页]

作者: 刘宁    时间: 2012-3-16 01:20
标题: 匿名内部类的返回值问题,求救,谢谢!
interface Inter
{
        void method();
}

class Test
{
      public static Inter function()
        {
                return new Inter()
                {
                        public void method()
                        {
                                System.out.println("haha");
                        }
                };
        }

}
public static void main(String[] args)
{
     Test.function().method();
}
在这个匿名类的练习中,有个问题不理解,我看了好多遍还是看不懂,求救。
Test.function():Test类中有个静态的方法function。这个我懂。
.method:function这个方法运行后的结果是一个对象,而且是个Inter的对象。
所以我的问题:返回值为为什么是Inter?
作者: 蒙武辉    时间: 2012-3-16 01:37
返回值为为什么是Inter?因为你把函数定义为Inter类型。所以必须返回一个Inter对象。
作者: 贠(yun)靖    时间: 2012-3-16 01:39
interface Inter
{
        void method();
}

class Test
{
      public static Inter function()
        {
               Inter in = new Inter()
                {
                        public void method()
                        {
                                System.out.println("haha");
                        }
                };
         return in;        给你把代码改一下就清楚了,只是省略了 Inner s = new Inner()    直接把等号后面的全部返回了,不就是一个对象了吗?
        }

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





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