Chitta Ranjan Mahato wrote:Can we create an instace of an interface? do inteface have constructors?
Yes you can create an instance of an interface using the anonymous inner class syntax and providing implementation of all the methods of the interface. Interfaces and Anonymous inner classes both can't have a constructor. But you can create an instance initializer block in the anonymous inner class.
Chitta Ranjan Mahato wrote:Please Explain this code.
I would say, technically you can NEVER create an instance of an interface, however you can implement an interface. The method described above is simply creating an implementation of the interface, not an instance of the interface.
Remember that a class that implements an interface should pass the IS-A test for that interface.
Every class has a default constructor, which has no parameters, you are creating an annoymous inner class of type Sweety.
The compilor knows this and will create a default constructor for your annoymous inner class.
Chitta Ranjan Mahato wrote:Can we create an instace of an interface? do inteface have constructors?
No, you cannot create an instance of an interface, nor can you create an instance of an abstract class. I.e., you cannot use the new keyword with an interface or abstract class. Interfaces do not have constructors.
Rob Prime wrote:But as Gavin said, you can create anonymous classes that implement one single interface / extend one single (abstract) class.
Yeah. In fact, you have to create a class that implements them. Raising anonymous inner classes only confuses the issue, since the implementing class is hidden. It may look like you're creating an instance of the interface, but of course, you're not. The basic simple fact is that you cannot create an instance of an interface or abstract class.