Can you create Interface object?


No, it is not possible. Designers did not provide a way. Of course, it is of common sense also. Because interface contains only abstract methods and as abstract methods do not have a body (of implementation code), we cannot create an object.

Suppose even if it is permitted, what is the use. Calling the abstract method with object does not yield any purpose as no output. No functionality to abstract methods.

Then, what is the use of interfaces in Java design and coding. They can be used as prototypes from which you can develop new classes easily. They work like templates for other classes that implement interface just like a blue print to construct a building.

But, it is possible to create Interface object with inner classes and anonymous objects as in the following code.
interface Test  
{  
  void greet();  
}  
public class Demo  
{  
  public static void main(String[] args)  
  {  
    Test t = new Test()  
     {  
       public void greet()  
       {  
         System.out.print("\nHi, Best wishes to way2java.com\n");  
       }  
    };  
    t.greet();  
    }  
}  


Interface object
Output screenshot on Interface object

Let us answer one more question.

Can we create an object of abstract class where all methods are non-abstract (concrete)? Answer for this is also "no". The answer for this is already discussed in Can we instantiate an abstract class?

Let us dig more on interfaces to play with. For in and outs of interfaces read: Topics related to In and Outs of interfaces.

4 thoughts on “Can you create Interface object?”

    1. SessionFactory is an interface for which you cannot create an object. Here, we are obtaining an object (by using a factory method buildSessionFactory()) of SessionFactory. To know more of factory methods (read http://way2java.com/awt-graphics/fontmetrics-factory-methods/).

      One SessionFactory object represents one database. In our program it represents Oracle database. Suppose you would like to connect to another database like MySQL, you require another SessionFactory. But from one SessionFactory, you can create any number of sessions.

  1. Okay I agree for you, but as a anonymous class, could we create the object for interface.
    i.e
    interface Any{
    public int add();
    }
    class Add implements Any{
    public int Add()
    {
    return 1+2;
    }
    public static void main(String args[])
    {
    Any a1 = new Any(){
    public int add()
    {
    return 3+4;
    }
    };
    }
    }
    This is the way we can get the object for an interface.
    But my doubt is , who will provide the constructor for this interface?

Leave a Comment

Your email address will not be published.