[英]is it possible to create object for interface without implementing this by any of the classes in java?
Itest is an Interface. Itest是一个接口。 here i mentioned like new Itest().
在这里我提到过像新的Itest()。 Then is it means that i can create object for interface?
那是否意味着我可以为接口创建对象?
public interface Itest {
}
static final Itest s = new Itest(){
};
It is just like, we could create object for interface without any class implement the interface. 就像我们可以为接口创建对象,而无需任何类实现接口。
It sounds like what you are looking for is anonymous classes . 听起来您正在寻找的是匿名类 。
They are most commonly used something like this: 它们最常用的是这样的:
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;
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.