Interfaces
An interface is a contract: the guy writing the interface says, “hey, I accept things looking that way“, and the guy using the interface says “Ok, the class I write looks that way“.
An interface is an empty shell, there are only the signatures of the methods, which implies that the methods do not have a body. The interface can’t do anything. It’s just a pattern.
Implementing an interface consumes very little CPU, because it’s not a class, just a bunch of names, and therefore there is no expensive look-up to do. It’s great when it matters such as in embedded devices.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
|
// I say all motor vehicles should look like this: interface MotorVehicle { void run(); int getFuel(); } // my team mate complies and writes vehicle looking that way class Car implements MotorVehicle { int fuel; void run() { print("Wrroooooooom"); } int getFuel() { return this.fuel; } } |
Abstract classes
Abstract classes, unlike interfaces, are classes. They are more expensive to use because there is a look-up to do when you inherit from them.
Abstract classes look a lot like interfaces, but they have something more : you can define a behavior for them. It’s more about a guy saying, “these classes should look like that, and they have that in common, so fill in the blanks!”.
e.g:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
|
// I say all motor vehicles should look like this : abstract class MotorVehicle { int fuel; // they ALL have fuel, so why not let others implement this? // let's make it for everybody int getFuel() { return this.fuel; } // that can be very different, force them to provide their // implementation abstract void run(); } // my team mate complies and writes vehicle looking that way class Car extends MotorVehicle { void run() { print("Wrroooooooom"); } } |