我们如何在java中创建接口对象? [英] How can we create object of interface in java?

查看:240
本文介绍了我们如何在java中创建接口对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这段代码是如何工作的我完全感到困惑....

How is this code working i m totally puzzled....

package com.servletpack.examples;

interface check {
    public void message();
}
public class Interface {
    public static void main(String[] args) {
        try {
            check t = new check() {//how????????????????
                public void message() {
                    System.out.println("Method defined in the interface");
                }
            };
            t.message();
        } catch (Exception ex) {
            System.out.println("" + ex.getMessage());
        }
    }
}


推荐答案

使用该语法,您可以创建匿名类 ,这是完全合法的。

With that syntax, you create an anonymous class, which is perfectly legal.

在内部,匿名类被编译为自己的类,称为 EnclosingClass $ n 封闭类的名称在 $ 符号之前。和每个额外的匿名类增加 n 。这意味着正在创建以下类:

Internally, anonymous classes are compiled to a class of their own, called EnclosingClass$n where the enclosing class' name precedes the $ sign. and n increases for each additional anonymous class. This means that the following class is being created:

class Interface$1 implements check {
     public void message() {
         System.out.println("Method defined in the interface");
     }
}

然后,中的代码main 编译为在内部使用新定义的匿名类:

Then, the code in main compiles to internally use the newly-defined anonymous class:

check t = new Interface$1();
t.message();

这篇关于我们如何在java中创建接口对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆