Interfaces

  1. Consider the bubble sort algorithms:

    Bubble sort algorithm for an integer array:
       input: A = array of ANY kind of objects
              N = number of elements in A
    
       arrayIsSorted = false;
       while ( ! arrayIsSorted )
       {
          arrayIsSorted = true;
    
          for (i = 0; i < N-1; i++)
          {
             if ( A[i] & A[i+1] are out of place )    
    	 {  swap A[i] & A[i+1]
    	    arrayIsSorted = false;
    	 }
          }
       }
    
    

    Type dependent information in the sort algorithm:

    • How to determine if objects A[i] and A[i+1] are in the wrong order

    • This property is also a requirement to sort objects:

      • In order to sort a certain type of objects, the objects must have the property that they can be ranked using a compare method

      • For instance: you cannot sort fruit objects because you can't rank apples & oranges

  2. The requirement description can be done by specifying the required set of methods that a class MUST implement

  3. Interface:

    • A interface consists of:

      • A set (possible empty) of constant definitions

      • A set (usually not empty) of abstract method definitions

      NOTE: A abstract method definition consists of a method name, method parameter list and a return type but DO NOT contain a method body

    • A interface DOES NOT contain any variables !!!

    • All methods & constants in a interface are AUTOMATICALLY declared as public

  4. Example Interface:

    An Example of Interface:
       public interface Compare
       { 
          // Usage: x.compareWith(y)
          // To determine the ranking between objects x and y 
          int compareWith(Object other);
    
    		// Note: it actually read:
    		//   public int compareWith(Object other);
       }
    
    

    The result of x.compareWith(y) is interpreted as:

    • x.compareWith(y) < 0     if x preceeds y
    • x.compareWith(y) == 0   if x ranks the same as y
    • x.compareWith(y) > 0     if x succeeds y

    (Just like the compareTo() method of Strings)

  5. You must define the parameter other as Object.

    WHY ?

    Because...

  6. An interface can be used as a class to define object variables

    Example: defining object variables using an interface
        Compare x;
    
        x.compareWith(...) // method "compareWith" is defined in "Compare"  
    
    

  7. An interface CANNOT be used to instantiate objects (new)

    Example: This is forbidded....
        Compare x = new Compare();  // ERROR !!!  
    
                // cannot use "new" on interface
                // new can ONLY be used on classes     
    
    

  8. What can you do with object variables defined with interfaces ???

    • We can use the Compare interface to define a generic sort algorithm

    Defining a generic sort algorith with "Compare":
       public class Sort
       {
    
          public static void sortThem(Compare obj[])
          {
             int        N = obj.length;   // Number of objects in array
             boolean    Done;
             int        i, k;
             Compare Help;   // Help variable for swapping
    
             Done = false;
             k = 1;
             while (! Done)
             {  Done = true;
    
                for (i = 0; i < (N - 1); i++)
                {  
    	       if ( obj[i].compareWith(obj[i+1]) > 0 )
                   {  // Wrong order, swap obj[i] & obj[i+1]
    		  Help     = obj[i];
                      obj[i]   = obj[i+1];
                      obj[i+1] = Help;
                      Done = false;
                   }
                }
                k = k + 1;
             }
          }
       }
    
    

    • Notice that we did NOT use any new operation.

    • Because sortThem takes as input an array obj[] of Compare objects, the sortThem method will sort an array of Compare objects

    • But... we CANNOT instantiate objects with an interface Compare...

      In other words: we CANNOT create objects of the type Compare. If you can't make these objects, what's the point of sorting them ???

    • So what is interface good for ????


    The $6,000,000 answer....

  9. A class can implement an interface

    The class that implement an interface MUST define ALL the methods mentioned in the interface

  10. Example:

    • An integer-like class that implement the Compare interface:

    Example: MyInteger class that implements the Compare interface
       public class MyInteger implements Compare
       {
          public int value;    // Value of MyInteger object
          
          public int compareWith(Object other)
          {
    	MyInteger help = (MyInteger) other; // Recover MyInteger object
    
    	if ( this.value < help.value ) // Can't use "other.value"
    	   return(-1);
    	else if ( this.value > help.value )
    	   return(1);
    	else 
    	   return(0);
    	
          } 
       }
    
    

    How the compareWith() method is normally used:

       MyInteger x = new MyInteger(...);
       MyInteger y = new MyInteger(...);      
    
       if ( x.compareWith(y) < 0 )
          System.out.println("x < y");
       else if ( x.compareWith(y) > 0 )
          System.out.println("x > y");
       else 
          System.out.println("x == y");
    

  11. EXTREMELY Important Facts:

    • An interface has the same functionality as (is equivalent to) a class
      (only difference is you cannot create objects of the interface type with the new operator).

    • A class that implements an interface is a subclass (child class) of that interface

    • You can convert object variables between the interface parent class and child class

    Example: Converting object reference variables between MyInteger & Compare
       MyInteger i = new MyInteger();   // You can create MyInteger objects
       Compare  x;                      // You cannot create Compare objects
    
       x = i;               // is allowed because Compare    
    	                // is "parent" of MyInteger
    
       i = (MyInteger) x;   // is allowed, but make sure
    			// x refers to a "MyInteger" object
    

  12. How to use the generic sort algorthm on MyInteger:

    Example: sorting integer
        public class SortInteger
        {
           public static void main()
           {
    	  Make an array of 4 MyInteger objects
    
    	  // Assign values to MyInteger array
    	  A[0] = new MyInteger(65);
    	  A[1] = new MyInteger(78);
    	  A[2] = new MyInteger(25);
    	  A[3] = new MyInteger(1);
    
              System.out.println("Initial array:");
              for (i = 0; i < N; i++)
                 System.out.println(A[i]);
              System.out.println();
    
    	  Sort.sortThem(A); // Is allowed, because A is 
    			    // an array of MyInteger
    			    // and MyInteger is a child class
    			    // of Compare !!!
    
              System.out.println("After Sort.sortThem(A):");
              for (i = 0; i < N; i++)
                 System.out.println(A[i]);
              System.out.println();
           }
        }
    

  13. Sorting Integer DEMO programs:

  14. How to use the generic sort algorthm on Strings:

    • You must first add (extend) the compareWith:

      Example: MyString class implements Compare interface
         // This class "packages" an String with a "compareWith" method
      
         public class MyString implements Compare
         {
            String s;
            public MyString(String x)
            {
      	 s = x;
            }
      
            // implement compareWith
            public int compareWith(Object other)
            {
      	MyString help = (MyString) other; // Recover MyString object
      
      	return( this.s.compareTo(help.s) );
            } 
         }
      
      

    • How to sort Strings that implements the Compare interface:

      Example: program to sort Strings
          public class SortString
          {
             public static void main()
             {
      	  Make an array A of 4 MyString objects
      
      	  // Assign values to MyString array
      	  // Assign values to MyInteger array
      	  A[0] = new MyString("hello");
      	  A[1] = new MyString("World");
      	  A[2] = new MyString("ABC");
      	  A[3] = new MyString("abc");
      
                System.out.println("Initial array:");
                for (i = 0; i < N; i++)
                   System.out.println(A[i]);
                System.out.println();
      
      	  Sort.sortThem(A); // Is allowed, because A is 
      			    // an array of MyString
      			    // and MyString is a child class
      			    // of Compare !!!
      
                System.out.println("After Sort.sortThem(A):");
                for (i = 0; i < N; i++)
                   System.out.println(A[i]);
                System.out.println();
             }
          }
      

    • Sorting Strings DEMO programs:

  15. Sorting BankAccount objects by balance:

    • Change BankAccount to implement the Compare interface:

      Example: BankAccount class implements Compare interface
         public class BankAccount implements Compare
         {
            .... // Other variables & definitions omitted for brevity 
            ....
      
            // Note that we pass in an "Object" other
            public int compareWith(Object other)
            {
      	 BankAccount help = (BankAccount) other; 
      		// Retrieve the BankAccount object
      
               if (this.balance - help.balance < 0)
      	    return(-1);
      	 else if (this.balance - help.balance > 0)
      	    return(1);
               else
                  return(0);
            } 
         }
      

    • How to sort BankAccount that implements the Compare interface:

      Example: program to sort BankAccount objects
          public class SortBankAccount
          {
             public static void main()
             {
      	  Make an array A of 4 BankAccount objects
      
      	  A[0] = new BankAccount(5000);
      	  A[1] = new BankAccount(4000);
      	  A[2] = new BankAccount(8000);
      	  A[3] = new BankAccount(1000);
      
                System.out.println("Initial array:");
                for (i = 0; i < N; i++)
                   System.out.println(A[i].getBalance());
                System.out.println();
      
      	  Sort.sortThem(A); // Is allowed, because A is 
      			    // an array of BankAccount
      			    // and BankAccount is a child class
      			    // of Compare !!!
      
                System.out.println("After Sort.sortThem(A):");
                for (i = 0; i < N; i++)
                   System.out.println(A[i].getBalance());
                System.out.println();
             }
          }
      

    • DEMO programs:

  16. Sorting BankAccount objects by balance, the more elegant object oriented approach.

    • Suppose you DO NOT have the source code of the BankAccount class...

    • Can you still use the Compare interface and the generic sort method defined with Compare to sort BankAccount objects ???

      The OOP approach...
         public class MyBankAccount 
                extends BankAccount implements Compare
         {
            public MyBankAccount(double init_amount)
            {
      	 super(init_amount);
            }
      
            
            public int compareWith(Object other)
            {
      	 MyBankAccount help = (MyBankAccount) other; 
      		// Retrieve the BankAccount object
      
               if (this.getBalance() - help.getBalance() < 0)
      	    return(-1);
      	 else if (this.getBalance() - help.getBalance() > 0)
      	    return(1);
               else
                  return(0);
            } 
         }
      

    • Sorting MyBankAccount objects that implements the Compare interface should now be a piece of cake:

      Example: program to sort MyBankAccount objects
          public class SortMyBankAccount
          {
             public static void main()
             {
      	  Make an array A of 4 MyBankAccount objects
      
      	  A[0] = new MyBankAccount(5000);
      	  A[1] = new MyBankAccount(4000);
      	  A[2] = new MyBankAccount(8000);
      	  A[3] = new MyBankAccount(1000);
      
                System.out.println("Initial array:");
                for (i = 0; i < N; i++)
                   System.out.println(A[i].getBalance());
                System.out.println();
      
      	  Sort.sortThem(A); // Is allowed, because A is 
      			    // an array of MyBankAccount
      			    // and MyBankAccount is a child class
      			    // of Compare !!!
      
                System.out.println("After Sort.sortThem(A):");
                for (i = 0; i < N; i++)
                   System.out.println(A[i].getBalance());
                System.out.println();
             }
          }
      

    • DEMO programs:


Footnote: