Why are we implementing, for example ICloneable or IDisposable. I'm not asking what ICloneable or IDisposable do, but I want to learn what's a good reason to implement these interfaces rather than just writing a method which disposes or clones our objects?
An implementation of an interface is a Java program that references the interface using the implements keyword. The program is required to provide method logic for all non-default methods. Optionally, the program can provide an implementation of a default method defined in the interface.
Yes, it is mandatory to implement all the methods in a class that implements an interface until and unless that class is declared as an abstract class. Implement every method defined by the interface.
When a class implements an interface, you can think of the class as signing a contract, agreeing to perform the specific behaviors of the interface. If a class does not perform all the behaviors of the interface, the class must declare itself as abstract. A class uses the implements keyword to implement an interface.
Using interfaces keeps the use of those pieces of functionality consistent. That way, when another class wants to / needs to use your class, it can act on it as a cloneable, disposable object without worrying about your particular implementation details.
By implementing a well known interface, you can have polymorphism, which enable you to write generic code that can act on any instance of a class that implementes a given interface.
You can check the Wikipedia article on polymorphism for more.
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