Is it possible to create an object of an interface in java?

10,235

Solution 1

You never create an instance of just the interface. You can have a field/parameter/local variable of that interface type, but that's fine - the value that is assigned to such a variable will always be either null or a reference to an instance of some concrete implementation of the interface. The point is that code which deals only with the interface shouldn't need to care what the implementation is.

A good example is Collections.shuffle(List) - I can provide that any list implementation, and it will only use the methods declared in the interface. The actual object will always be an instance of some concrete implementation, but the shuffle method doesn't need to know or care.

Solution 2

There are two ways to get a usable interface class. If we have the interface:

public interface Vehicle{
    public void drive();
}

The first is, as you say to have a class which implements the interface:

public class Car implements Vehicle{
    public void drive(){
        System.out.println("Here in my car I feel safest of all);
    }
}
Vehicle car = new Car();
v.drive();

Or you can create an anonymous class:

Vehicle v = new Vehicle(){
    public void drive(){
        System.out.println("Hello world");
    }
};
v.drive();

Solution 3

You don't create an Instance of the interface - you create an instance of a class which implements the interface. You can create as many different implementations as you like and choose the one which fits best.

In your code you can use a implementation where an object conforming to the interface is required.

Solution 4

The interface is a special class with an abstract type so it can't create an instance of her self because it doesn't have a type.It has some methods and keeps the type of classes the implements her. So you can create only reference variables and they refers to an object and sure the class of the object must implement the interface.

Share:
10,235
Ashwin
Author by

Ashwin

https://github.com/ashwinbhaskar

Updated on June 05, 2022

Comments

  • Ashwin
    Ashwin almost 2 years

    In java, an interface contains only the method type, name and parameters. The actual implementation is done in a class that implements it. Given this, how is it possible to create an instance of a interface and use it as if it were a class object? There are many such interfaces, such as org.w3c.dom.Node.

    This is the code that I am using:

    DocumentBuilderFactory fty = DocumentBuilderFactory.newInstance();
    fty.setNamespaceAware(true);
    DocumentBuilder builder = fty.newDocumentBuilder();
    ByteArrayInputStream bais = new ByteArrayInputStream(result.getBytes());
    Document xmldoc = builder.parse(bais);
    NodeList rm1 = xmldoc.getElementsByTagName("Subject");
    Node rm3 = rm1.item(0);