黑马程序员技术交流社区

标题: 【分享】面试题 [打印本页]

作者: 目前是菜鸟    时间: 2016-5-25 23:07
标题: 【分享】面试题

  按照要求,补齐代码
  interface Inter { void show(); }
  class Outer { //补齐代码 }
  class OuterDemo {
   public static void main(String[] args) {
      Outer.method().show();
     }
  }
  要求在控制台输出”HelloWorld”
# 代码以及分析
class Test {
public static void main(String[] args) {
   Outer.method().show();      /*
          从这句话开始分析,Outer是类,用类名.去调用method()方法,说明method()方法是静态的,但不确定其返回值类型,Outer.method()可以调用show()方法,说明
          Outer.method()是一个对象,也就是说method()方法的返回值是一个对象,而show()方法是在接口内的,并且show()方法一定是非静态的,因为接口内的方法一定是
          抽象的,而抽象的是不能和静态的一起共用的,非静态的方法一定要创建对象才能调用,说明Outer.method()的返回值是一个对象,对象才能调用show()方法,而有
          show()方法的只有Inter,所以method()方法的返回值的类型一定是Inter类型,返回值一定是Inter对象,又因为Inter是接口,
          所以在method()方法的内部,只需返回Inter的子类对象(匿名内部类)即可
         */
}
}
//按照要求,补齐代码
interface Inter {
void show();
}
class Outer {
public static Inter method() {
  return new Inter() {
   public void show() {
    System.out.println("helloWorld");
   }
  };
  
}
}
//要求在控制台输出”HelloWorld”

作者: hjbing456    时间: 2016-5-25 23:42
public static Inter method() {
   return new Inter() {
    public void show() {
     System.out.println("helloWorld");
    }
   };
   
}
作者: hmCEO    时间: 2016-5-25 23:55
多谢  分享
作者: LRBlucky    时间: 2016-5-25 23:58
感谢好人  收藏了
作者: Hyperion    时间: 2016-5-26 21:18
mark一下
作者: 罗勇    时间: 2016-5-26 21:30
学过了,过来复习一下!!!顺便支持一下




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