简体   繁体   中英

is it possible to create object for interface without implementing this by any of the classes in java?

Itest is an Interface. here i mentioned like new 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;
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM