Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/323.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 尽管接口可以';不能实例化吗?_Java - Fatal编程技术网

Java 尽管接口可以';不能实例化吗?

Java 尽管接口可以';不能实例化吗?,java,Java,我声明了以下接口 public interface MyInterface { void do_it_now(); } 这是我能做的 public class MainClass{ public static void main(String[] args) { MyInterface mainClass = new MyInterface() { @Override public void do_it_n

我声明了以下接口

public interface MyInterface {

    void do_it_now();
} 
这是我能做的

public class MainClass{

    public static void main(String[] args) {
        MyInterface mainClass = new MyInterface() {

            @Override
            public void do_it_now() {


            }
        };

    }

}
现在我对上述代码的问题是,根据定义,接口不能被实例化 在java中,我们可以有一个实例变量类型的接口。新MyInterface()行的含义是什么

我想知道引擎盖下发生了什么

对于我的问题,我也经历了相当微妙的过程。但我对这个答案并不十分满意


如果您发现我的问题很愚蠢,请不要给出负面反馈或阻止我的帐户发表评论,我将删除它。

能够拥有接口类型的变量允许您为该变量分配实现该接口的任何类的实例。然后,您可以使用该变量执行该实例的接口方法,而不必关心所使用的具体实现。它使您的代码更加通用,因为您可以切换到不同的接口实现,而无需更改使用接口类型变量的代码。

您正在第二个代码块中创建一个“匿名类”。这意味着它创建了一个实现您编写的接口或类的类。它基本上是创建实现接口(MyInterface)的子类的简捷方法

我想知道引擎盖下发生了什么

考虑下面的代码,假设您的问题中定义了接口
MyInterface

定义了两个内部类;第一个类是匿名的(没有名字),第二个类命名为
MyClass
。这两个类中的每一个都实现了MyInterface

// declare variable of type MyInterface
MyInterface myVariable;

// assign the variable to an instance of anonymous class that implements MyInterface
myVariable = new MyInterface() { 
    @Override
    public void do_it_now() {
    }
};

// define a named class that implements MyInterface
class MyClass implements MyInterface { 
    @Override
    public void do_it_now() {
    }
}

// assign the variable to an instance of named class that implements MyInterface
myVariable = new MyClass();

幕后发生的事情是,java编译器编译
newMyInterface(){…}
编译成一个名为
$1.class
的单独类文件,就像它将
MyClass
编译成一个名为
MyClass$1.class

的单独类文件一样。你正在创建一个实现接口的匿名类,这个类可以创建一个实例。顺便说一句,这个问题并不愚蠢。我建议你看一下字节码,看看发生了什么。尝试
javap-cmainclass
javap-cmainclass$1