Interfaces

Dr Andy Evans

[Fullscreen]

Interfaces

  • Interfaces are the ultimate abstract class.
  • They are lists of methods that must be defined in classes that implement them. All variables in them are final.
  • Why the devil would you want to do that...?
  • You can make classes that rely on finding certain methods wherever they are used. By forcing people to implement these methods you can guarantee they exist.
	
BlueBankRequest  b1 = 
		new BlueBankRequest();
b1.setPin (getAtmPin());
boolean pinOk = 
    redBankConnection.isPinOk(b1);

	
boolean isPinOk (GenericRequest qr) {
    if (qr.getPin() == customerPin) {
		return true;
    } else { 
		return false;
    }
}

Here then, is our banking example. Let's imagine, now, that GenericRequest is an interface, not a class. What would it look like?

Interfaces

	
public interface GenericRequest {

    public int getPin ();

}


	
public class BlueBankRequest 
				    implements GenericRequest  {
    private int pin = 0;

    public void setPin (int p) { 
		pin = p; 
    }

    public int getPin () {
		return pin;
    }
}

Interfaces are *so* important, that they have their own keywords to define and inherit them.
	
BlueBankRequest  b1 = 
		new BlueBankRequest();
b1.setPin (getAtmPin());
boolean pinOk = 
    redBankConnection.isPinOk(b1);

	
boolean isPinOk (GenericRequest qr) {
    if (qr.getPin() == customerPin) {
		return true;
    } else { 
		return false;
    }
}

In short, the process is identical.

Inheritance

  • We can extend a Class to give us all its functionality.
    	
    class A extends B {
    
    
  • We can implement an Interface, which means we promise to supply its methods.
    
    class A implements C {
    
    
  • We can only extend one Class, but we can implement many Interfaces using commas.
    	
    class A extends B implements C, D, E {
    
    

interface variables

Interfaces classically also contain final static variables of use with the interface:
	
interface GenericRequest {

    final static String STANDARDS_AGENCY = 
				"Bank Standards Inc.";
    int getPin ();

}

	
BlueBankRequest  b1 = new BlueBankRequest();
b1.setPin (1234);
boolean ok = redBankConnection.isPinOk(b1);
System.out.printToATM
    ("Your connection is brought to you by " +
	GenericRequest.STANDARDS_AGENCY);