I know it\'s not possible to define a constructor in an interface. But I\'m wondering why, because I think it could be very useful.
So you could be sure that some fi
This is because interfaces do not allow to define the method body in it.but we should have to define the constructor in the same class as interfaces have by default abstract modifier for all the methods to define. That's why we can not define constructor in the interfaces.
See this question for the why (taken from the comments).
If you really need to do something like this, you may want an abstract base class rather than an interface.
If you want to make sure that every implementation of the interface contains specific field, you simply need to add to your interface the getter for that field:
interface IMyMessage(){
@NonNull String getReceiver();
}
Receiver object has to be passed to the class in some way (either by constructor or by setter)A work around you can try is defining a getInstance() method in your interface so the implementer is aware of what parameters need to be handled. It isn't as solid as an abstract class, but it allows more flexibility as being an interface.
However this workaround does require you to use the getInstance() to instantiate all objects of this interface.
E.g.
public interface Module {
Module getInstance(Receiver receiver);
}
There is only static fields in interface that dosen't need to initialized during object creation in subclass and the method of interface has to provide actual implementation in subclass .So there is no need of constructor in interface.
Second reason-during the object creation of subclass, the parent constructor is called .But if there will be more than one interface implemented then a conflict will occur during call of interface constructor as to which interface's constructor will call first
Dependencies that are not referenced in an interfaces methods should be regarded as implementation details, not something that the interface enforces. Of course there can be exceptions, but as a rule, you should define your interface as what the behavior is expected to be. Internal state of a given implementation shouldn't be a design concern of the interface.