是否有可能为接口创建对象而不通过java中的任何类实现它?

时间:2010-03-12 10:36:35

标签: java interface

Itest是一个界面。在这里我提到了新的Itest()。那么这是否意味着我可以为界面创建对象?

public interface Itest {


}
static final Itest s = new Itest(){
}; 

就像我们可以为接口创建对象而没有任何类实现接口。

2 个答案:

答案 0 :(得分:2)

听起来你正在寻找的是anonymous classes

它们最常用的是:

interface Something { void execute(); }

// In some code...
setSomething(new Something() {
   public void execute() { 
       // Your code here
   }
});

答案 1 :(得分:0)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication2
{      
    interface ISampleInterface
    {
        void SampleMethod();
    }

    class ImplementationClass : ISampleInterface
    {
        // Explicit interface member implementation: 
       public void SampleMethod()
        {
            // Method implementation.
            Console.Write("Interface implements");  
        }

        static void Main(string[] args)
        {
            // Declare an interface instance.
            ISampleInterface obj = new ImplementationClass();

            // Call the member.
            obj.SampleMethod();
            ImplementationClass a = new ImplementationClass();
            a.SampleMethod();
            ISampleInterface b = (ISampleInterface)a;
        }
    }
}
相关问题