A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© Stevenj 中级黑马   /  2014-7-7 08:36  /  1496 人查看  /  5 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

//-------------------------------------------------110 匿名内部类_练习题
interface Inter {
        void method();
}

class Test {
        //补足代码,通过匿名内部类
        /*
        static class Inner implements Inter {        //??????????????
                public voic method() {
                        System.out.println("method run");
                }
        }
        */
       
        static Inter function() {
                //return new Inner();
                return new Inter() {                //不用再写 static 了吗????????????
                        public void method() {
                                System.out.println("method run");
                        }
                };
        }
}

class M {
        public static void main(String[] args) {
                Test.function().method();//849function()直接被类名调用,所以它一定是静态的。
        }
}

5 个回复

倒序浏览
看不懂,不知道你的代码补了没有
回复 使用道具 举报
LZ,我去翻了内部类的视频,发现第一个?处的代码是多余的。练习要求补足的代码是第二个?处的代码。
如果是关于第二个?的代码为什么这么写,我认为:
Test.function().method();可知,Test类中有一个function()方法,且因为是直接调用,所以是静态的。然后因为它又继续调用method()方法,而method方法是接口inter的一个方法。所以function方法一定返回一个Inter的子类对象,并复写了method方法。由此需要用到匿名内部类。new匿名类时不能加static修饰符(虽然该匿名类其实是静态的)。
当然也可以不用匿名内部类,
那补足的代码为:
  1. static class Inner implements Inter {        
  2.     public void method() {
  3.         System.out.println("method run");
  4.     }
  5.         }
  6.         static Inter function(){
  7.             return new Inner();
  8.         }
复制代码



回复 使用道具 举报
学习了  
回复 使用道具 举报
你第一个问号处
如果你定义了一个静态内部类 那么你就不必再在function()中定义匿名内部类,可以这样写
static Inner function(){
       return new Inner();
}

第二个问号处:  你既然定义了匿名内部类,如果你写static  你想写在哪?  定义匿名内部类时再复写Inter中的方法就可以创建一个子类对象,具有function()方法并可以调用function();方法
回复 使用道具 举报
看不懂!
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马