Books Related to Java Technology

Saturday, December 27, 2008

What is Interface?

An interface is a contract between a class and the outside world. When a class implements an interface, it promises to provide the behavior of the interface. Interfaces are similar to abstract classes but all methods are abstract and all properties are static final. As an example, we will build a Working interface for the subclasses of Man. 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 reserved word 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 WorkingMan extends Man implements Working {
public WorkingMan(String name) {
super(name);
}
public void work(){
speak();
System.out.println("interface implemented");
}
}

No comments:

Post a Comment