Itest是一个接口。这里我提到像新的Itest()。那么这是否意味着我可以为接口创建对象?是否有可能为接口创建对象,而无需通过java中的任何类实现此目标?
public interface Itest {
}
static final Itest s = new Itest(){
};
这就好比,我们可以为没有任何类实现接口的接口创建对象。
Itest是一个接口。这里我提到像新的Itest()。那么这是否意味着我可以为接口创建对象?是否有可能为接口创建对象,而无需通过java中的任何类实现此目标?
public interface Itest {
}
static final Itest s = new Itest(){
};
这就好比,我们可以为没有任何类实现接口的接口创建对象。
这听起来像你在找什么是anonymous classes。
他们最常用的是这样的:
interface Something { void execute(); }
// In some code...
setSomething(new Something() {
public void execute() {
// Your code here
}
});
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;
}
}
}
这看起来像C#代码。这个问题是关于Java的。 – 2017-07-08 12:18:45
如果要测试你需要嘲讽。寻找一个嘲笑库作为jMock。 – onof 2010-03-12 10:44:45