Saturday, April 23, 2011

Interfaces in java

Interfaces are similar to abstract classes but all methods are abstract and all properties are static final. Interfaces can be inherited (ie. you can have a sub-interface). As with classes the extends keyword is used for inheritence.Java does not allow multiple inheritance for classes (ie. a subclass being the extension of more than one superclass). An interface is used to tie elements of several classes together. Interfaces are also used to separate design from coding as class method headers are specified but not their bodies. This allows compilation and parameter consistency testing prior to the coding phase. Interfaces are also used to set up unit testing frameworks.
As an example, we will build a Working interface for the subclasses of Animal. Since this interface has the method called work(), that method must be defined in any class using the Working interface.

public interface Working
{
  public void work();
}

When you create a class that uses an interface, you reference the interface with the phrase implements Interface_list. Interface_list is one or more interfaces as multiple interfaces are allowed. Any class that implements an interface must include code for all methods in the interface. This ensures commonality between interfaced objects.


public class WorkingDog extends Dog implements Working
{
  public WorkingDog(String nm)
  {
    super(nm);    // builds ala parent
  }
  public void work()  // this method specific to WorkingDog
  {
    speak();
    System.out.println("I can herd sheep and cows");
  }
}


Also see Multiple inheritance in java

No comments:

Post a Comment

Chitika