简体   繁体   English

是否可以创建接口对象而不用Java中的任何类来实现?

[英]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.

相关问题 在Java中是否可以为接口创建注释,从而强制实现类的构造函数的特定参数列表 - Is it possible in Java to create an Annotation for an interface, forcing implementing classes a specific parameter list for the constructor Java对象序列化而不实现可序列化接口 - Java object serialized without implementing serializable interface 是否可以在java中创建接口的对象? - Is it possible to create an object of an interface in java? Java-是否可以在任何对象上调用接口方法? - Java - Is it possible to call an interface method on a any object? 是否有任何Java标准类在没有实现Collection的情况下实现Iterable? - Are there any Java standard classes that implement Iterable without implementing Collection? 是否可以在Java中为Runnable接口创建对象 - Is it possible to create object for Runnable interface in java Java:传递对象实现接口 - Java: passing object implementing interface Java - 使用Object参数实现接口 - Java - Implementing interface with Object argument 将对象分配给接口变量而不实现接口 - Assigning object to interface variable without implementing interface 创建实现接口的所有类的向量 - Create vector of all classes implementing an interface
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM