我可以为界面创建对象吗? [英] Can I Create Object For Interface?

查看:79
本文介绍了我可以为界面创建对象吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以为界面创建对象,如果是,我们怎么办?
根据我的观点,下面的代码说我们可以:

Is it possible to creating object for an interface, if yes how can we? according to my view the following code says that we can:

Runnable r = new Runnable(){
/ /某些实现
}

推荐答案

这不是创建Interface的实例,它正在创建一个实现接口的类。所以当你写的时候

This is not creating the instance of Interface, it is creating a class that implements interface. So When you write

    Runnable runnable = new Runnable() {

        @Override
        public void run() {
            // TODO Auto-generated method stub

        }
    };

您实际上是在创建一个实现Runnable接口的类。
你需要遵循这里的所有规则,在这里,我们重写 runnable的运行方法

You are actually a creating a class that is implementing the Runnable interface. You need to follow all rules here, here, we are overriding the run method for Runnable

 There is similar thing for abstract class also. We can test using an example

public abstract class AbstractClass {

    public void someMethod(){
        System.out.println("abstract class");
    }

}

和另一个类别 TestClass

public class TestClass {

    public static void main(String[] args) {

        AbstractClass abstractClass = new AbstractClass() {
            public void someMethod() {
                System.out.println("concrete class method");
            }
        };
        abstractClass.someMethod();
    }
}

这将创建一个子类的实例,我们在其中覆盖 someMethod();
此程序打印

This will create the instance of a subclass in which we are overriding someMethod(); This program prints

concrete class method

这证明我们正在创建子类的实例。

This proves we are creating the instance of subclass.

这篇关于我可以为界面创建对象吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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