Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Must a class adhere to the documented contract of an interface to be said to implement that interface

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?

like image 354
Raphael Roth Avatar asked Jun 18 '16 14:06

Raphael Roth


1 Answers

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.

like image 157
JB Nizet Avatar answered Oct 09 '22 14:10

JB Nizet