Answer the question
In order to leave comments, you need to log in
When should you use interfaces (Java) in your code?
Good day! I read that using interfaces in Java is important and good practice. But I do not have a clear understanding of when they should be used in the code. I would be very happy to see use cases with a rationale for why they are used.
Answer the question
In order to leave comments, you need to log in
DevMan is right - by paradigm always!
In practice, any written code (class or interface) requires time to create and maintain. Maintaining a primitive class is easier than maintaining a primitive class and its interface.
Therefore, in practice, interfaces are usually written:
1. As a necessary part of patterns;
2. If "interface is an interaction contract": a library or component is being developed, here interfaces are part of an immutable contract;
3. Good practice - do all services with interfaces. Many JAVA frameworks are pushing for this, as an example: Spring and OSGi ( Apache Felix );
4. For JUnit testing. Example: when testing business logic, real services are replaced by test stubs. Accordingly, business logic classes should use interfaces that, during real work, are replaced by real implementations, and in a test environment - by test stubs.
1, Abstraction is needed wherever the axis of system changes will take place. And the interface is the main means of achieving abstraction in Java. Item 2 follows from this.
2. Whenever an abstraction is needed (with the exception of cases when the abstraction must have a state. In this case, an abstract class will have to be used instead of an interface, since an interface cannot have a state).
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question