Interfaces

Document Sample
Interfaces Powered By Docstoc
					                        Interfaces

• Need arising from software engineering
   – Disparate groups of programmers need to agree to a
     “contract” that spells out how their software interacts
   – Write your own code without seeing the implementation of
     other classes (by other programmers)
   – An Interface is such a “contract”
• An interface declares a type of object by
  specifying what the object does
   – Doesn’t care about the implementation
   – Only what functionality is provided
   – Specifies common operations
                     Example

Car manufacturers               Guidance manufacturers
Car: start, stop,               Invoke the car methods for
accelerate, turn right, …       navigation

                There has to be an industry
                standard as to which methods
                should be implemented by all
                car manufacturers
                  Another motivation

• Multiple inheritance
   – A class inherits from more than one parents
       • A Dog can be both an Animal and a Speaker
       • Jack can be both a Person and an Employee
   – In C++, a class can inheritance from more than one classes
   – In Java, multiple inheritance is done through multiple
     interfaces
                             Interfaces

• A collection of constants and abstract methods
   – without any implementation!
    public interface Animal{
        int LEGS=4;       // constants
        public void sleep(); // abstract methods
        . . .
    }

    Note:
    •    No {} in the method declaration – no implementation
    •    The word “abstract” is not needed
• Different from abstract classes
   – Abstract class can also have variables and non-abstract methods
     (with implementation).
                      Use an Interface

• Writing a class the implements an interface
   – Provides implementation for each method defined in the
     interface
    public class Dog implements Animal{
        public void sleep(){
                                             not extends!
            System.out.println(“Snorrrr”);
        }
    }


• An interface cannot be instantiated
                        Multiple Inheritance
interface Speaker{          class Dog implements Speaker, Animal {
    public void speak();        public void speak(){
}                                System.out.println("woof");
interface Animal{               }
    final int LEGS=4;           public void sleep(){
    public void sleep();            System.out.println("snorrrr");
}                               }
                                public String toString(){
                                    String s="This Dog has " + LEGS + " legs.";
                                 return s;
                                }
                            }
class Teacher implements Speaker{       public class ExInterfaces {
    private String thoughts;              public static void main(String[]
                                        args){
    public Teacher (String t) {
                                                Dog little = new Dog();
        thoughts=t;
                                                little.speak();
    }
                                                little.sleep();
    public void speak () {
                                                System.out.println(
        System.out.println(thoughts);
                                                  little.toString() );
    }
                                            Teacher tom = new Teacher("Do your
    public void repeat() {
                                        homework");
        for (int i=1; i<=3; i++)
                                                tom.speak();
        System.out.println(thoughts);
                                                tom.repeat();
    }
                                            }
}
                                        }
  Converting Between Class and Interface
                 Types
• Very similar to the case of converting between
  superclass and subclass references
   – Converting from class to interface reference
     Teacher t = new Teacher();
     Speaker sp = t; //OK
     …

      method: public void test(Speaker speaker){…}
     You can call this method by test(t);

      sp.repeat(); //Error
   – Converting from interface reference to class reference
       Teacher teacher = (Teacher) sp;
       t.repeat();
               Some Useful Interfaces

• Comparable
  – the compareTo() method:
      public interface Comparable{
        public int compareTo(Object o);
      }
  – String implements Comparable
  – Why is it useful? Ex: Arrays.sort(Object[] a)
• Listener
  – Useful for applications that handle events
  – Will be discussed next week
         Introduction to Polymorphism

• Polymorphism
  – “having many forms”
  – Helps build extensible systems
  – Programs generically process objects as superclass objects
      • Can add classes to systems easily
          – Classes must be part of generically processed hierarchy
  – Can be done through interfaces and abstract classes
                                  Example

public class ExInterfaces {
    public static void main(String[] args){
        Speaker current;
        current = new Dog();
        current.speak();
        current = new Teacher("Do your homework");
        current.speak();
    }
}

Different speak() method will be called depending on what
type of objects the current reference points to.
The decision as to which one to call cannot be done at
compile time. It has to wait until execution time.
          Using if-else Statements?

• if-else-based system
  – Determine appropriate action for object
     • Based on object’s type
  – Error prone
     • Programmer can forget to make appropriate type test
     • Adding and deleting if-else statements
class Animal {
    //...
}
class Dog extends Animal {
    public void woof() {                             Example: using if-else
        System.out.println("Woof!");                 and instanceof
    }
    //...
}
class Cat extends Animal {
    public void meow() {
        System.out.println("Meow!");
    }
    //...
}
class Example5 {
    public static void main(String[] args) {
        makeItTalk(new Cat());
        makeItTalk(new Dog());
    }
    public static void makeItTalk(Animal animal) {
        if (animal instanceof Cat) {
            Cat cat = (Cat) animal;
            cat.meow();
        }
        else if (animal instanceof Dog) {
            Dog dog = (Dog) animal;
            dog.woof();
        }
    }
}
             Dynamic Method Binding

• Dynamic method binding
  –   Also called “late binding”
  –   Implements polymorphic processing of objects
  –   Use superclass reference to refer to subclass object
  –   Program chooses “correct” method in subclass at execution
import java.util.Scanner;
public class AnimalGame                                Example
{
      public static void main(String[] args)
      {
            System.out.println("Choose one of three doors by entering
                 the number of the door you choose.");
            Scanner input = new Scanner(System.in);
            int doorNumber = input.nextInt();

            Animal animal = null;               Animal is an interface
            if (doorNumber == 1){              Dog and Cat implement Animal
                   animal = new Cat();
            }
            else if (doorNumber == 2){
                   animal = new Dog();
            }
            else {
                   System.out.println("Not a valid door number");
                   System.exit(1);
            }

            System.out.println("The animal behind your door says: " +
                                animal.talk());
    }
}
       Dynamic Method Binding (cont.)

• Example
  – Superclass Shape
  – Subclasses Circle, Rectangle and Square
  – Each class draws itself according to type of class
      • Shape has method draw
      • Each subclass overrides method draw
      • Call method draw of superclass Shape
          – Program determines dynamically which subclass draw
             method to invoke
         Late Binding vs. Early Binding

• Early Binding
   – Overloaded methods/constructors
   – E.g., two constructors for BankAccount class
      • BankAccount() and BankAccount(double)
      • The compiler selects the correct constructor when compiling
        the program by looking at the parameters.
         account = new BankAccount(); //compiler selects BankAccount();
         account = new BankAccount(1.00);//BankAccount(double)

• Early Binding – decisions are made at compilation
  time by the compiler
• Late Binding – decision are made at run time by
  the java virtual machine
    Case Study: A Payroll System Using
              Polymorphism
• Abstract methods and polymorphism
  – Abstract superclass Employee
     • Method earnings applies to all employees
     • Person’s earnings dependent on type of Employee
  – Concrete Employee subclasses declared final
     • Boss
     • CommissionWorker
     • PieceWorker
     • HourlyWorker
                          Employee



   Boss     CommissionWorker      PieceWorker      HourlyWorker
1    // Employee.java                   abstract class cannot be instantiated
2    // Abstract base class Employee.
3
4    public abstract class Employee {
5       private String firstName;                                             Employee.java
6       private String lastName;            abstract class can have instance data
7                                          and nonabstract methods for subclasses 4
                                                                              Line
8       // constructor
9       public Employee( String first,   String last )                        abstract class
10      {                                                                     cannot be instantiated
11         firstName = first;
12         lastName = last;               abstract class can have constructors for
13      }                                                                          Lines 5-6 and 16-30
14
                                            subclasses to initialize inherited dataabstract class can
15      // get first name                                                       have instance data and
16      public String getFirstName()
17      {                                                                       nonabstract
18         return firstName;                                                    methods for subclasses
19      }
20
21      // get last name                                                        Lines 9-13
22      public String getLastName()                                             abstract class can
23      {                                                                       have constructors for
24         return lastName;
25      }                                                                       subclasses to initialize
26                                                                              inherited data
27      public String toString()
28      {
29         return firstName + ' ' + lastName;
30      }
31
32       // Abstract method that must be implemented for each
33       // derived class of Employee from which objects
34       // are instantiated.
35       public abstract double earnings();
36                                                                Employee.java
37   }   // end class Employee
                                      Subclasses must implement   Line 35
                                         abstract method          Subclasses must
                                                                  implement abstract
                                                                  method
1    // Boss.java                             Boss is an Employee subclass
2    // Boss class derived from Employee.
3
4    public final class Boss extends Employee {
5       private double weeklySalary;                                            Boss.java
                                                    Boss inherits Employee’s public
6
                                                       methods (except for constuctor)
7        // constructor for class Boss                                          Line 4
8        public Boss( String first, String   last, double salary )
9        {                                                                      Boss is an Employee
10          super( first, last ); // call    superclass constructor             subclass
11          setWeeklySalary( salary );
12       }                                         Explicit call to Employee
13                                                  constructor using super  Line 4
14       // set Boss's salary                                                Boss inherits
15       public void setWeeklySalary(   double salary )                      Employee’s public
16       {
17          weeklySalary = ( salary >   0 ? salary : 0 );                    methods (except for
18       }                                                                   constuctor)
19                                              Required to implement Employee’s
20       // get Boss's pay
21       public double earnings()
                                                method earnings (polymorphism) 10
                                                                             Line
22       {                                                                   Explicit call to
23          return weeklySalary;                                             Employee constructor
24       }
25                                                                           using super
26       // get String representation of Boss's name
27       public String toString()                                              Lines 21-24
28       {
29          return "Boss: " + super.toString();                                Required to implement
30       }                                                                     Employee’s method
31                                                                             earnings
32   }   // end class Boss
                                                                               (polymorphism)
1    // CommissionWorker.java                CommissionWorker is       an
2                                                Employee subclass
     // CommissionWorker class derived from Employee
3
4    public final class CommissionWorker extends Employee {
5       private double salary;      // base salary per week                 CommissionWorker
6       private double commission; // amount per item sold                  .java
7       private int quantity;       // total items sold for week
8
9       // constructor for class CommissionWorker                           Line 4
10      public CommissionWorker( String first, String last,                 CommissionWorker
11         double salary, double commission, int quantity )                 is an Employee
12      {
13         super( first, last ); // call superclass constructor             subclass
14         setSalary( salary );
15         setCommission( commission );         Explicit call to Employee
                                                                            Line 13
16         setQuantity( quantity );               constructor using super
17      }                                                                   Explicit call to
18                                                                          Employee constructor
19      // set CommissionWorker's weekly base salary                        using super
20      public void setSalary( double weeklySalary )
21      {
22         salary = ( weeklySalary > 0 ? weeklySalary : 0 );
23      }
24
25      // set CommissionWorker's commission
26      public void setCommission( double itemCommission )
27      {
28         commission = ( itemCommission > 0 ? itemCommission : 0 );
29      }
30
31       // set CommissionWorker's quantity sold
32       public void setQuantity( int totalSold to implement Employee’s
                                       Required )
33       {
                                     method earnings; this implementation
34          quantity = ( totalSold > 0 ? totalSold : 0 );
35       }                                  differs from that in Boss       CommissionWorker
36                                                                          .java
37       // determine CommissionWorker's earnings
38       public double earnings()
39       {                                                                  Lines 38-41
40          return salary + commission * quantity;                          Required to implement
41       }                                                                  Employee’s method
42
43       // get String representation of CommissionWorker's name            earnings; this
44       public String toString()                                           implementation differs
45       {                                                                  from that in Boss
46          return "Commission worker: " + super.toString();
47       }
48
49   }   // end class CommissionWorker
1    // PieceWorker.java                     PieceWorker is an
2                                             Employee subclass
     // PieceWorker class derived from Employee
3
4    public final class PieceWorker extends Employee {
5       private double wagePerPiece; // wage per piece output                 PieceWorker.java
6       private int quantity;        // output for week
7                                                                             Line 4
8         // constructor for class PieceWorker
9         public PieceWorker( String first, String last,                      PieceWorker is an
10           double wage, int numberOfItems )                                 Employee subclass
11        {
12           super( first, last ); // call superclass constructor
13           setWage( wage );                                                 Line 12
14           setQuantity( numberOfItems);         Explicit call to Employee   Explicit call to
15    }                                            constructor using super    Employee constructor
16
17        // set PieceWorker's wage                                           using super
18        public void setWage( double wage )
19        {                                                                   Lines 30-33
20           wagePerPiece = ( wage > 0 ? wage : 0 );
21        }                                                                   Implementation of
22                                                                            Employee’s method
23        // set number of items output                                       earnings; differs
24        public void setQuantity( int numberOfItems )
25        {                                                                   from that of Boss and
26           quantity = ( numberOfItems > 0 ? numberOfItems : 0 );            CommissionWorker
27        }
28                                              Implementation of Employee’s method
29        // determine PieceWorker's earnings    earnings; differs from that of Boss
30        public double earnings()
31        {                                          and CommissionWorker
32           return quantity * wagePerPiece;
33        }
34
35       public String toString()
36       {
37          return "Piece worker: " + super.toString();
38       }
39                                                        PieceWorker.java
40   }   // end class PieceWorker
1    // HourlyWorker.java                     HourlyWorker is an
2    // Definition of class HourlyWorker       Employee subclass
3
4    public final class HourlyWorker extends Employee {
5       private double wage;   // wage per hour                              HourlyWorker.jav
6       private double hours; // hours worked for week                       a
7
8       // constructor for class HourlyWorker
9       public HourlyWorker( String first, String last,                      Line 4
10         double wagePerHour, double hoursWorked )                          PieceWorker is an
11      {                                                                    Employee subclass
12         super( first, last );    // call superclass constructor
13         setWage( wagePerHour );
14         setHours( hoursWorked );              Explicit call to Employee   Line 12
15      }                                         constructor using super    Explicit call to
16
17      // Set the wage                                                      Employee constructor
18      public void setWage( double wagePerHour )                            using super
19      {
20         wage = ( wagePerHour > 0 ? wagePerHour : 0 );
21      }                                                                    Line 31
22                                                      Implementation of Employee’s method
                                                                             Implementation of
23      // Set the hours worked                          earnings; differs from that of other
                                                                             Employee’s method
24      public void setHours( double hoursWorked )             Employee subclasses
25      {                                                                    earnings; differs
26         hours = ( hoursWorked >= 0 && hoursWorked   < 168 ?               from that of other
27            hoursWorked : 0 );                                             Employee subclasses
28      }
29
30      // Get the HourlyWorker's pay
31      public double earnings() { return wage * hours; }
32
33       public String toString()
34       {
35          return "Hourly worker: " + super.toString();
36       }
37                                                         HourlyWorker.jav
38   }   // end class HourlyWorker                         a
1    // Test.java
2    // Driver for Employee hierarchy
3
4    // Java core packages
5    import java.text.DecimalFormat;                                         Test.java
6
7    // Java extension packages                                           Line 15
8    import javax.swing.JOptionPane;     Test cannot instantiate Employee Test cannot
9
10   public class Test {                       but can reference one      instantiate Employee
11                                                                        but can reference one
12      // test Employee hierarchy
13      public static void main( String args[] )
14      {                                                      Instantiate one instance each of
                                                                                Lines 18-28
15         Employee employee; // superclass reference              EmployeeInstantiate one instance
                                                                                 subclasses
16         String output = "";
17                                                                              each of Employee
18         Boss boss = new Boss( "John", "Smith", 800.0 );                      subclasses
19
20          CommissionWorker commisionWorker =
21            new CommissionWorker(
22            "Sue", "Jones", 400.0, 3.0, 150 );
23
24        PieceWorker pieceWorker =
25          new PieceWorker( "Bob", "Lewis", 2.5, 200 );
26
27        HourlyWorker hourlyWorker =
28           new HourlyWorker( "Karen", "Price", 12.5, 40 );
29
30       DecimalFormat precision2 = new DecimalFormat( "0.00" );
31
32   // Employee reference to a Boss   Use Employee to reference Boss
33   employee = boss;
34
35   output += employee.toString() + " earned $" +
36      precision2.format( employee.earnings() ) + "\n" +               Test.java
37      boss.toString() + " earned $" +
38      precision2.format( boss.earnings() ) + "\n"; Method  employee.earnings
                                                                        Line 33
39
40   // Employee reference to a CommissionWorker
                                                        dynamically binds to Employee to
                                                                        Use method
41   employee = commissionWorker;                           boss.earnings Boss
                                                                        reference
42
43   output += employee.toString() + " earned $" +
44      precision2.format( employee.earnings() ) + "\n" +             Line 36
45      commissionWorker.toString() + " earned $" +                   Method
46      precision2.format(                                            employee.earning
47         commissionWorker.earnings() ) + "\n";
48                                                                    s dynamically binds to
                                                     Do same for CommissionWorker
49   // Employee reference to a PieceWorker                and PieceWorker
                                                                      method
50   employee = pieceWorker;                                          boss.earnings
51
52   output += employee.toString() + " earned $" +
53      precision2.format( employee.earnings() ) + "\n" +               Lines 41-55
54      pieceWorker.toString() + " earned $" +                          Do same for
55      precision2.format( pieceWorker.earnings() ) + "\n";
56                                                                      CommissionWorker
                                                                        and PieceWorker
57        // Employee reference to an HourlyWorker
58        employee = hourlyWorker;
59        ((HourlyWorker)employee).setWage(13.75);
60        output += employee.toString() + " earned $" +
61        precision2.format( employee.earnings() ) + "\n" +                      Test.java
62             hourlyWorker.toString() + " earned $" +
63             precision2.format( hourlyWorker.earnings() ) + "\n";             Lines 58-63
64
65            JOptionPane.showMessageDialog( null, output,                      Repeat for
66               "Demonstrating Polymorphism",                                  HourlyWorker
67               JOptionPane.INFORMATION_MESSAGE );     Repeat for HourlyWorker
68
69            System.exit( 0 );                                                 Line 59
70       }                                                                      Casting is required for
71                                                                              accessing subclass
72   }   //   end class Test
                                                                                methods
                                                                  Casting required for accessing
                                                                        subclass methods
      New Classes and Dynamic Binding

• Dynamic binding (late binding)
   – Object’s type need not be known at compile time
   – At run time, call is matched with method of called object
   – Easy to add new classes to the class hierarchy




         Read the lecture notes on the course Web site for
         another example on polymorphism.
                    Recap - Interfaces

• Interfaces
   – A collection of constants and abstract methods
   – No implementation details defined
       public interface Car{
           final int WHEELS = 4;
           public void start();
           public void stop();
           . . .
       }
   – Variables are implicitly defined as public   static final
• Implementing interfaces
   public class Ford implements Car {
     public void start(){
       . . .
     }
     public void stop(){
       . . .
     }
     . . .
   }
                          Interfaces

• True or false?
   – An interface can have private instance attributes
   – A concrete class implementing an interface can implement
     selected methods defined in the interface
   – A class can implement more than one interface
   – One need to use abstract to indicate that a method is
     abstract in an interface
   – You can create an instance (object) of an interface, just like
     creating an instance of a class
interface Silly {                      class SillyBird extends Bird {
   public void narf();
   public void poit(Silly s);              public SillyBird(){
}                                             System.out.println("duchess");
public class Bird implements Silly {       }
   public static void main(String
   args[]) {
                                           public SillyBird(int i) {
     System.out.println("zero");
                                              super(i);
     Silly s = new SillyBird(1);
                                           }
     Silly s2 = new Loony();
     s.poit(s2);
                                           public void narf() {
     s2.poit(s);
                                              System.out.println("drum");
     System.out.println("zymurgy");
                                              super.narf();
   }
                                           }
   public Bird() {
                                       }
     this(0);
     System.out.println("zircon");
                                       class Loony extends SillyBird {
   }
                                          public Loony() {
   public Bird(int i) {
     System.out.println("zanzibar");       System.out.println("stupendous");
   }                                       }
   public void narf() {                    public void narf() {
     System.out.println("zort");             System.out.println("snark");
   }                                       }
   public void poit(Silly s) {         }
      s.narf();
   }                                          What’s the output?
}

				
DOCUMENT INFO
Shared By:
Categories:
Tags:
Stats:
views:5
posted:8/10/2012
language:
pages:34