A good example of when exactly to use interfaces specifically in Java would be ideal and any specific rulings that apply.
In Java, an interface specifies the behavior of a class by providing an abstract type. As one of Java's core concepts, abstraction, polymorphism, and multiple inheritance are supported through this technology. Interfaces are used in Java to achieve abstraction.
No, every class should not have an interface. It's overkill squared. You use an interface when you need to abstract what's done from how it's done, and you're certain that the implementation can change.
Interfaces are appropriate when you are really defining a contract between two objects that is invariant over time. Abstract base types are better for defining a common base for a family of types.
You should use an interface if you want a contract on some behavior or functionality. You should not use an interface if you need to write the same code for the interface methods. In this case, you should use an abstract class, define the method once, and reuse it as needed.
A good place to look at would be the collections framework.
java.util.List //interface java.util.ArrayList //Concrete class java.util.LinkedList //Concrete class
So you can write code like this:
List l = new ArrayList(); l.add(..) //do something else.
If in future you want to change the implementation with say LinkedList
or you own AwesomeList which implements List
interface, all you have to do is change the very first line to:
List l = new MyAwesomeList(); or List l = new LinkedList();
The rest of the code would follow through.
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