Search code examples
javainterfaceinstanceanonymous-class

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


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);

Solution

  • 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.