2016-11-28 Interfaces

posted Nov 28, 2016, 7:11 AM by Samuel Konstantinovich   [ updated Nov 28, 2016, 11:02 AM ]
Goal: INter  your  FACE!


In real life, objects have interfaces like buttons and switches.
In java, methods form an object's interface with the outside world.

In java:
Interfaces in Java allow us to create a collection of methods to guarantee a class's interaction. 
An interface does not contain method implementation, constructors, or instance variables.
The keyword interface is used to define this collection of methods.

Interfaces are often named as an adjective. Some are nouns (see List in java) but
the idea that the adjective can describe what it can do is more in the spirit of what an interface is.
Examples of adjective interface names: cloneable, comparable, runnable
( or the fictional ones like: smashable , killable, fixable, etc)

Example of creation of an interface:

public interface Washable 
  void mop(); 
  void scrub(int times); 
  void scrape(int times); 

class Floor implements Washable
   // The compiler will now require that methods
   // mop, scrub, and scrape
   // all be implemented. Compilation will fail if those
   // methods are missing from this class.
The last AP had the students write an interface. We won't write a lot of them, you need to know it.

Abstract classes vs Interfaces:

An abstract class’s purpose is to provide a superclass from which other classes can inherit and thus share a common design. 
This CAN include instance variables, and some concrete methods.
Abstract classes:
1. let you define some behaviors; and force your subclasses to provide others. 
2. are an excellent way to create planned inheritance hierarchies, as they are a good choice for non-leaf classes.
3. Limit a class to extend ONE abstract class.

Interfaces do not have any implementation. They are not classes, and cannot have any instance variables.
1. They are good when you want unrelated classes to share a behavior. 
2. They allow a single class to implement multiple behaviors. e.g. both Breakable and Fixable

Interfaces you should be aware of: