Sam Thompson wrote:Hi everyone...
What do you/can you use interfaces for exactly? And how would you implement them in programming?
S.T.
Hey Sam!
There's
alot of good answers already so I'll just try to build on it. As was mentioned, Java doesn't allow multiple inheritances so your class can only have one superclass. However, you can also "implement" an interface which gives (actually requires) that your class has certain methods, fields, etc. But how does it help you?
Let's say you work for Amazon. They ship all sorts of products - computers, books, etc. These items may all be derived classes in your Java code (ie. super class = Computer, subclass = MacBookPro). Now, Amazon is going to ship all of these items so they need to have certain pieces of information attached to all their goods - weight, dimensions, insured value, etc. Now, you may ask - why not just have those values stored in the a superclass "Inventory" of which computer is derived? ( Inventory -> Computer -> MacBookPro ) Well, Amazon doesn't just ship goods to customers. Perhaps the ship equipment & supplies internally from one warehouse to another. They may track their scanning gun in Java as something like Equipment -> ScanGun. Well, the scanning gun isn't something Amazon sells so it's class isn't derived from "Inventory". However, we can implement an interface called "Shipment" to both the MacBook and the scanning gun.
Not only does the interface "Shipment" add the proper variables and methods we need to process a MacBook or scanning gun as a shipment, but it allows BOTH to be treated in Java AS a Shipment. So we can write a method in Java called something like shipThis(Shipment item) and it can send a MacBook, scanning gun or whatever else implements "Shipment".
Hope this makes some sort of sense. Ha ha!