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

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© Moonboy2014 中级黑马   /  2014-6-14 22:44  /  1444 人查看  /  5 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

interface Inter
{
        void method();
}
class Test
{
        public static void function()
        {
                 new Inter()
                {
                        public void method()
                        {
                                System.out.println("method run!");
                        }
                };
        }
}
class TestDemo4
{
        public static void main(String[] args)
        {
                Test.function().method();
        }
}
请教各位高手,这段代码问题出在哪,知道的请详细解答一下,感谢!

5 个回复

倒序浏览
哥们,你其中有一句我不太懂,就是new Inter(){{}};看样子应该是一条语句,我不知道这是什么知识点?请指教啊,:o:o我只知道这样能实现:
  1. interface Inter
  2. {
  3.         void method();
  4. }
  5. class Test
  6. {
  7.         public static void function()
  8.         {
  9.                 class S implements Inter
  10.                 {
  11.                         public void method()
  12.                         {
  13.                                 System.out.println("method run!");
  14.                         }
  15.                 }
  16.                  new S().method();
  17.         }
  18. }
  19. class TestDemo11
  20. {
  21.         public static void main(String[] args)
  22.         {
  23.                 Test.function();
  24.         }
  25. }
复制代码

:lol
回复 使用道具 举报
  1. interface Inter
  2. {
  3.        void method();
  4. }
  5. class Test
  6. {
  7.         public static void function()
  8.         {
  9.                 Inter i = new Inter()          //生成一个Inter对象,但是Inter只是一个接口,需要通过匿名类的方式实现这个接口并返回一个对象
  10.                 {
  11.                         public void method() //这里只是实现了接口中的抽象方法,并没有调用
  12.                         {
  13.                                 System.out.println("method run!");
  14.                         }
  15.                         
  16.                 };
  17.                
  18.                 i.method();//这里通过Inter的对象来调用里面的method方法
  19.         }
  20. }
  21. public class TestDemo4
  22. {
  23.         public static void main(String[] args)
  24.         {
  25.                 Test.function(); //你的代码:Test.function().method();本身的书写是错误的,相当于你通过一个方法调用另一个方法,方法只能通过类或者对象调用。
  26.         }
  27. }
复制代码


需要注意的地方:
1.非静态方法需要通过对象来调用,静态方法需要通过类来调用
2.方法只有通过调用才能执行,只声明方法不会执行
回复 使用道具 举报
Seraphim 发表于 2014-6-15 11:32
需要注意的地方:
1.非静态方法需要通过对象来调用,静态方法需要通过类来调用
2.方法只有通过调用才能执 ...

受教了:handshake
回复 使用道具 举报
好吧,错过了回答时间了,同志们智慧无限啊。
回复 使用道具 举报
y200745 发表于 2014-6-15 17:20
好吧,错过了回答时间了,同志们智慧无限啊。

高手在民间。。。。。。。。。。。。。。。。
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马