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

那年仲夏 提交于 2019-12-09 09:46:54

问题


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.


回答1:


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




回答2:


It does not make sense to provide an Constructor in an Interface.

Check if it makes sense for you to provide a default initialize() method instead.




回答3:


Constructors are when the objects come into picture and the fact that a object for an interface cannot be constructed is SOUND, be it Java, C# or Java8

So... if you have any functionality that you would want to define by default in the interface level, Java8 introduces the concept of Default Methods.




回答4:


You need to add the default constructor to the class you want to serialize.




回答5:


Yes, kind of! You can do:

public interface MyInterface {
  MyInterface NO_OP = new MyInterface() {};
}


来源:https://stackoverflow.com/questions/22810921/is-there-a-way-to-add-a-default-constructor-to-an-interface

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!