I know what implementing an interface means (technically), but I'm not sure if I understand what the "contract" encompasses:
Lets say I make a class MyList
which implements java.util.List
(that is, I implement all methods with code that compiles), is MyList
a List
then? OR do I need to read all the comments of the methods I override and make sure my implementation fulfils these "expectation" on the behaviour?
Technically, yes, MyList
is a List
if it implements all the methods of the List
interface. But the compiler is no magician. It can't check that your methods do what they should do. And of course, every method should do what its documentation says it does.
If I receive a List
, and this List
is an instance of MyList
, and I call list.add("foo")
, I expect "foo" to be added at the end of the list. Not to be removed, or added twice, or whatever other behavior. So, of course, if your class implements List
, its methods should comply with the contract defined in its API documentation.
Imagine you sell cars. I go to your shop, and buy a car. To me, it's a car because it looks like all the other cars: it has wheels, pedals, windows, etc. But if I press the accelerator, it brakes, and when I turn lights on, it honks, and when I open the windows, it accelerates and kills a poor kid on the road, I won't be happy at all and you'll be in trouble because the car you sold me isn't behaving correctly.
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