There must be a good reason why Java designers didn’t allow any state to be defined in interfaces . Can you please throw some light on this aspect of design decision ?
5
An interface is a contract specifying what its implementer promises to be able to do. It does not need to specify state because state is an implementation detail and only serves to constrain implementers in how this contract is fulfilled. If you want to specify state you might want to rethink you use of interfaces and look at abstract base classes instead.
11
Because interfaces are meant to specify an abstraction.
A good abstraction should be as simple as possible, which means specifying as little as possible about implementation details. State is an implementation detail, and as such shouldn’t be included in your abstraction.
Java designers therefore made a pretty good decision to avoid including state in interfaces.
Alternatives to consider if you ever feel like that you want state in an interface:
- Use composition to plug together objects that have do state and implement your desired interfaces.
- Use an abstract base class (but be aware that this mixes interface and implementation and can get you into trouble if you are not careful)
An interesting video on this topic is “Simple made easy” by Rich Hickey. They key point is that if you mix things together that should be kept separate, you get into a mess…..
An interface by its nature is simply a specification of what an object should look like, by its very definition it doesn’t have state, its not just java its any language.
Because with state it would have been an abstract class; and since there is multiple inheritance allowed for interfaces => Java would have supported full multiple inheritance => diamond problem.
1
Just adding – an interface, by definition, doesn’t have state. That’s the definition of what an interface is, and if it had state then it wouldn’t be an interface any more.
If you need to use state then an interface is the wrong tool for the job you want to do. Maybe you’d be better off asking another question (and maybe on SO itself rather than here) describing exactly what the problem you’re encountering that is causing you to ask this question is, and you may get more help in finding a solution.
0