黑马程序员技术交流社区

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

作者: 张振纲    时间: 2012-7-31 01:04
标题: 匿名内部类
  1. interface AAA
  2. {
  3.         void show();
  4. }

  5. class Student
  6. {
  7.         public AAA SSS()
  8.         {
  9.                 new AAA()
  10.                 {
  11.                 public void show()
  12.                         {
  13.                         System.out.println("zhongguo");
  14.                         }
  15.                 }.show();
  16.        
  17.         };
  18. }
  19. class  Main
  20. {
  21.         public static void main(String[] args)
  22.         {
  23.                 new Student().SSS();
  24.         //new Student().new Inner().show();
  25.         }
  26. }
复制代码
错误提示,18行缺少返回语句,求指点
作者: 韦念欣    时间: 2012-7-31 01:09
第10行前加上return,例如: return new AAA()
作者: 周世阳    时间: 2012-7-31 01:13
public AAA SSS()这个方法被声明为返回类型为AAA,所以必须返回一个AAA子类型的实例(因为AAA是接口,所以实例必须是子类),在new AAA()前面加上reurn即可
作者: 王志明    时间: 2012-7-31 01:15
  1. interface AAA {
  2.         void show();
  3. }

  4. class Student {
  5.         // 你这里要返回AAA类型的对象,而你却没有返回
  6.         public AAA SSS() {
  7.                 return new AAA() {
  8.                         public void show() {
  9.                                 System.out.println("zhongguo");
  10.                         }
  11.                 };
  12.         };
  13. }

  14. class Main {
  15.         public static void main(String[] args) {
  16.                 // 分开写的话是:
  17.                 // AAA aaa = new Student().SSS();
  18.                 // aaa.show();
  19.                 new Student().SSS().show();
  20.         }
  21. }
复制代码
还有,楼主的类名和方法名要起的好点,最好能见名知意

作者: 纪艺松    时间: 2012-7-31 06:51
class  Student中的SSS方法要求返回一个AAA,一个方法的返回值必须通过return语句来完成,,我看你方法仅仅只是想通过匿名类调用接口中的方法show()
直接将SSS该成void得了;;;;
作者: 刘海源    时间: 2012-7-31 11:46
希望对你有帮助奥

)$M4_3~]JNX5T)Y4I4CAR@X.jpg (62.44 KB, 下载次数: 50)

)$M4_3~]JNX5T)Y4I4CAR@X.jpg





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