Interfaces

Document Sample
Interfaces Powered By Docstoc
					                      Interfaces

• Sometimes it is helpful to define what a class must do
  but not how it will do it.
• We have already seen an example of this: the abstract
  method.
• An abstract method defines the signature for a method
  but provides no implementation.
• A derived class must provide its own implementation of
  each abstract method defined by its base class.
• Thus, an abstract method specifies the interface to the
  method but not the implementation.


Interfaces                  tMyn                            1
• While abstract classes and methods are useful, it is
  possible to take this concept a step further.
• We can fully separate a class’s interface from its
  implementation by using the keyword interface.
• Interfaces are syntactically similar to abstract classes.
• However, in an interface, no method can include a body.
• That is, an interface provides no implementation
  whatsoever.
• It specifies what must be done, but not how.
• Once an interface is defined, any number of classes can
  implement it.
• Also, one class can implement any number of interfaces.


Interfaces                  tMyn                          2
• To implement an interface, a class must provide bodies
  (implementations) for the methods described by the
  interface.
• A class that does not implement all the methods of the
  interface (but does implement some of them) is an
  abstract class and must be declared abstract.
• Each class is free to determine the details of its own
  implementation.
• Thus, two classes might implement the same interface in
  different ways, but each class still supports the same set
  of methods.
• Thus, code that has knowledge of the interface can use
  objects of either class since the interface to those
  objects is the same.
Interfaces                  tMyn                           3
• By providing the interface keyword, Java allows you
  to fully utilize the “one interface, multiple methods”
  aspect of polymorphism.
• Polymorphism will be discussed later.
• When declaring a method in an interface, choose a
  method name that describes the method’s purpose in a
  general manner, because the method may be
  implemented by many unrelated classes.
• A general idea of an interface is that unrelated classes
  implement a set of common methods.
• All methods declared in an interface are implicitly
  public abstract methods.


Interfaces                  tMyn                             4
• It is proper style to declare an interface’s methods
  without keywords public and abstract, because they
  are redundant in interface method declarations.
• When an interface is declared public, it must be in a
  file of the same name.
• Methods are declared using only their return type and
  signature.
• Interfaces cannot be instantiated – they can only be
  implemented by classes or extended by other interfaces.
• If you do not specify that the interface is public, your
  interface will be accessible only to classes defined in the
  same package as the interface.


Interfaces                   tMyn                           5
       package TimoSoft;

       public interface ElectricalDevice
       {
         void powerOn();
         void powerOff();
       }


      package TimoSoft;

      public interface FrequencyTuner
      {
        void setFrequency();
        void getFrequency();
      }




Interfaces                                 tMyn   6
      package TimoSoft;

      public class ElectricFan implements ElectricalDevice
      {
        public ElectricFan()
        {
           System.out.println("ElectricFan constructor.");
        }
        public void powerOn()
        {
           System.out.println("The power is now on, ElectricFan.");
        }
        public void powerOff()
        {
           System.out.println("The power is now off, ElectricFan.");
        }
      }




Interfaces                             tMyn                            7
     package TimoSoft;

     public class MicroWaveOven implements ElectricalDevice
     {
       public MicroWaveOven()
       {
          System.out.println("MicroWaveOven constructor.");
       }
       public void powerOn()
       {
          System.out.println("The power is now on, MicroWaveOven.");
       }
       public void powerOff()
       {
          System.out.println("The power is now off, MicroWaveOven.");
       }
     }




Interfaces                           tMyn                               8
     package TimoSoft;

     public class CellPhone implements ElectricalDevice, FrequencyTuner
     {
       public CellPhone()
       {
          System.out.println("CellPhone constructor.");
       }
       public void powerOn()
       {
          System.out.println("The power is now on, CellPhone.");
       }
       public void powerOff()
       {
          System.out.println("The power is now off, CellPhone.");
       }




Interfaces                          tMyn                                  9
         public void setFrequency()
         {
           System.out.println("The frequency is now set, CellPhone.");
         }
         public void getFrequency()
         {
           System.out.println("This is the current frequency, CellPhone.");
         }
     }




Interfaces                              tMyn                                  10
       package TimoSoft;

       public class Notes implements FrequencyTuner
       {
         public Notes()
         {
            System.out.println("Notes constructor.");
         }
         public void setFrequency()
         {
            System.out.println("The frequency is now set to Middle C, Notes.");
         }
         public void getFrequency()
         {
            System.out.println("This is the current frequency, Notes.");
         }
       }



Interfaces                            tMyn                                    11
       package TimoSoft;

       public class Test
       {
         public static void main(String[] args)
         {
            MicroWaveOven first=new MicroWaveOven();
            first.powerOn();
            CellPhone second=new CellPhone();
            second.getFrequency();
            Notes third=new Notes();
            third.getFrequency();
         }                           run:
       }                             MicroWaveOven constructor.
                                     The power is now on, MicroWaveOven.
                                     CellPhone constructor.
                                     This is the current frequency, CellPhone.
                                     Notes constructor.
                                     This is the current frequency, Notes.
                                     BUILD SUCCESSFUL (total time: 1 second)

Interfaces                            tMyn                                  12
• Once an interface has been defined, one of more
  classes can implement that interface.
• To implement an interface, include the implements
  clause in a class definition and then create the methods
  defined by the interface.
• The methods that implement an interface must be
  declared public, because all members of an interface
  are implicitly public.
• It is both permissible and common for classes that
  implement interfaces to define additional members of
  their own.




Interfaces                  tMyn                             13
• The UML distinguishes an interface from other classes
  by placing the word interface in guillemets
  (<<interface>>) above the interface name. The UML
  expresses the relationship between a class and an
  interface through a relationship known as realization.
• A class is said to realize or implement, the methods of
  an interface.
• A class diagram models a realization as a dashed arrow
  with a hollow arrowhead pointing from the implementing
  class to the interface, Figure 1:




Interfaces                 tMyn                         14
             <<interface>>                              <<interface>>
             ElectricalDevice                           FrequencyTuner




  MicroWaveOven              ElectricFan            CellPhone            Notes




 Figure 1. A UML representation of the preceding example.




Interfaces                                   tMyn                                15
• Variables can be declared in an interface, but they are
  implicitly public, static, and final.
• Large programs typically make use of several constant
  values that describe such things as array size, various
  limits, special values, and the like.
• To define a set of shared constants, simply create an
  interface that contains only these constants.
• Let’s have a simple example to demonstrate:




Interfaces                  tMyn                            16
• Automobile engine yields a power output of 55000 watts
  while cruising. Convert that power value into horsepower
  value.
• The mechanical horsepower of a sport car is 375
  HP@6500rpm. Convert that horsepower value into
  watts.




Interfaces                 tMyn                          17
    package TimoSoft;

    public interface ConversionFactors
    {
      double HP_TO_WATT=745.7;
      double WATT_TO_HP=1.0/HP_TO_WATT;
    }




Interfaces                    tMyn        18
       package TimoSoft;

       public class SportCar implements ConversionFactors
       {
         public SportCar()
         {
            System.out.println("SportCar constructor");
         }
         public double FromHPToWatt(double hpVal)
         {
            return HP_TO_WATT*hpVal;
         }
         public double FromWattToHP(double wVal)
         {
            return WATT_TO_HP*wVal;
         }
       }



Interfaces                           tMyn                   19
         run:
         SportCar constructor
         The power of 55000 watts equals to 73.75620222609628 horsepower.
         The power of 375 horsepower equals to 279637.5 watts.
         BUILD SUCCESSFUL (total time: 0 seconds)




Interfaces                          tMyn                                20
• From the preceding example: All the constants in an
  interface ConversionFactors were implicitly public,
  static, and final, but those modifiers can be omitted
  – and typically will be omitted.
• Alternatively you can replace the interface from the
  preceding example and use the capability to import static
  members of a class into any class that needs any of
  those constants:




Interfaces                  tMyn                         21
       package TimoSoft;

       public class ConversionFactors
       {
         public static final double HP_TO_WATT=745.7;
         public static final double WATT_TO_HP=1.0/HP_TO_WATT;
       }




Interfaces                         tMyn                          22
       package TimoSoft;
       import static TimoSoft.ConversionFactors.*;
       public class SportCar
       {
         public SportCar()
         {
            System.out.println("SportCar constructor");
         }
         public double FromHPToWatt(double hpVal)
         {
            return HP_TO_WATT*hpVal;
         }
         public double FromWattToHP(double wVal)
         {
            return WATT_TO_HP*wVal;
         }
       }



Interfaces                            tMyn                23
      package TimoSoft;

      public class Test
      {
        public static void main(String[] args)
        {
           SportCar first=new SportCar();
           System.out.println("The power of 55000 watts equals to "+
                 first.FromWattToHP(55000.0)+" horsepower.");
           System.out.println("The power of 375 horsepower equals to "+
                 first.FromHPToWatt(375.0)+" watts.");
        }
      }
             run:
             SportCar constructor
             The power of 55000 watts equals to 73.75620222609628 horsepower.
             The power of 375 horsepower equals to 279637.5 watts.
             BUILD SUCCESSFUL (total time: 2 seconds)



Interfaces                          tMyn                                 24
• An interface can extend other interfaces, just as a class
  can extend another class (in inheritance relationships).
• However, whereas a class can extend only one other
  class, an interface can extend any number of interfaces.
• The interface declaration includes a comma-separated
  list of all interfaces that it extends:

    public interface GroupedInterface extends
    Interface1, Interface2, Interface3
    {
        void doSomething(int a, double b);
        String doSomethingElse(String s);
    }
Interfaces                  tMyn                          25
• The interface doing the extending acquires all the
  methods and constants from the interface it extends.
• When a class implements an interface that inherits
  another interface, it must provide implementations for all
  methods defined within the interface inheritance chain.




Interfaces                   tMyn                          26

				
DOCUMENT INFO