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.
Java compiler automatically creates a default constructor (Constructor with no arguments) in case no constructor is present in the java class.
The default constructor in Java initializes the data members of the class to their default values such as 0 for int, 0.0 for double etc. This constructor is implemented by default by the Java compiler if there is no explicit constructor implemented by the user for the class.
Interfaces can contain properties and methods, but not fields/variables. Interface members are by default abstract and public. An interface cannot contain a constructor (as it cannot be used to create objects)
No, this is not possible.
You may want to use an abstract class if you want implementations have a "default constructor".
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With