Asked by
Vidya Rani
in
Computers & Technology
at
12:35 PM on November 11, 2008
Dan Dan's Answer
An interface is an idea taken from Objective C. It describes the public methods that a class implements and their calling conventions without saying anything about how those methods are implemented. It is the responsibility of each class that implements an interface to provide code to handle the cases where the methods of the interface are called.
For example suppose you're writing an inventory database. The inventory may include many different items of many different types and classes. However each item in the warehouse needs to be able to tell you its price. Normally you would implement this by having each class extend a common superclass. However that's not always convenient. Instead you can declare an interface called Price with a price() method like this:
public interface Price {
public float price();
}
Any class which implements the Price interface must contain a method with the signature public float price(). The code of the price() method is included separately in each separate class which implements Price, not in the Price interface itself.
Different classes in your warehouse can each implement the Price interface like this:
public class Monopoly extends BoardGame implements Price {
// other methods
public float price() {
return 14.95;
}
}
When other code is passed an object, it can test whether the object implements Price with the instanceof operator. For example,
if (o instanceof Price) System.out.println("Subtotal is " + o.price());
In fact, interfaces can be used to tag objects. The java.rmi.Remote interface declares no methods. Its sole purpose is to indicate that an object is a remote object. In general, sub-interfaces of java.rmi.Remote will declare remote methods, however. For example,
public interface Hello extends java.rmi.Remote {
public String sayHello();
}
public class HelloImpl extends UnicastRemoteServer implements Hello {
public String sayHello() {
return "Hello";
}
}
Answered at
12:51 PM on November 11, 2008
Read all answers