is there a way to add a default constructor to an interface

Joshua Kissoon picture Joshua Kissoon · Apr 2, 2014 · Viewed 13.9k times · Source

With default methods now added to Java 8, is there any way to create a default constructor?

I've tried:

public interface KadContent<T>
{
    public default KadContent()
    {

    }
...

Getting the error <identifier> expected from Netbeans

Why Needed? I'm using Gson to serialize the objects and getting the "unable to invoke no-args constructor .." error and I do know that I can resolve this problem using Gson's InstanceCreator. But is there a way to create a default Constructor?

Update

I've found the problem with my own code. I was using

gson.fromJson(new String(data), InterfaceName.class);

instead of

gson.fromJson(new String(data), ClassName.class);

So even though the subclass had default constructors, the deserialization code was incorrect. But the question of default constructor still stands.

Answer

thobens picture thobens · Apr 2, 2014

No, this is not possible.

  1. It does not make sense in an interface
  2. If you implement an interface, the class has already a default constructor (the one without arguments)

You may want to use an abstract class if you want implementations have a "default constructor".