Easy to Learn Java: Programming Articles, Examples and Tips

Start with Java in a few days with Java Lessons or Lectures


Code Examples

Java Tools

More Java Tools!

Java Forum

All Java Tips


Submit News
Search the site here...
Search the JavaFAQ.nu
1000 Java Tips ebook

1000 Java Tips - Click here for the high resolution copy!1000 Java Tips - Click here for the high resolution copy!

Java Screensaver, take it here

Free "1000 Java Tips" eBook is here! It is huge collection of big and small Java programming articles and tips. Please take your copy here.

Take your copy of free "Java Technology Screensaver"!.

Easy Java Lecture 14: Interfaces and packages. Part I. Teach/learn online

JavaFAQ Home » Java Lectures by Anatoliy Malyarenko Go to all tips in Java Lectures by Anatoliy Malyarenko

Bookmark and Share

Interfaces and packages

by: Anatoliy Malyarenko


  • Contents of the lecture.
  • Creating interfaces.
  • Creating and using packages.

What is an interface?

An interface defines a protocol of behaviour that can be implemented by any class anywhere in the class hierarchy. An interface defines a set of methods but does not implement them. A class that implements the interface agrees to implement all the methods defined in the interface, thereby agreeing to certain behaviour.

Definition 1. An interface is a named collection of method definitions (without implementations). An interface can also declare constants. Because an interface is simply a list of unimplemented, and therefore abstract, methods, you might wonder how an interface differs from an abstract class. The differences are significant.

  • An interface cannot implement any methods, whereas an abstract class can.
  • A class can implement many interfaces but can have only one superclass.
  • An interface is not part of the class hierarchy. Unrelated classes can implement the same interface.

Suppose that you have written a class that can watch stock prices coming over a data feed. This class allows other classes to register to be notified when the value of a particular stock changes. First, your class, which we'll call StockMonitor, would implement a method that lets other objects register for notification:


public class StockMonitor {
    public void watchStock(StockWatcher watcher,
        String tickerSymbol, double delta) {

The first argument to this method is a StockWatcher object. StockWatcher is the name of an interface whose code you will see later. That interface declares one method: valueChanged. An object that wants to be notified of stock changes must be an instance of a class that implements this interface and thus implements the valueChanged method.

The other two arguments provide the symbol of the stock to watch and the amount of change that the watcher considers interesting enough to be notified of. When the StockMonitor class detects an interesting change, it calls the valueChanged method of the watcher.

The watchStock method ensures, through the data type of its first argument, that all registered objects implement the valueChanged method. It makes sense to use an interface data type here because it matters only that registrants implement a particular method. If StockMonitor had used a class name as the data type, that would artificially force a class relationship on its users. Because a class can have only one superclass, it would also limit what type of objects can use this service. By using an interface, the registered objects class could be anything -- Applet or Thread -- for instance, thus allowing any class anywhere in the class hierarchy to use this service.

Defining an interface

Fig. 1 shows that an interface definition has two components: the interface declaration and the interface body. The interface declaration declares various attributes about the interface, such as its name and whether it extends other interfaces. The interface body contains the constant and the method declarations for that interface.

Figure 1: The StockWatcher interface and the structure of an interface definition


public interface StockWatcher {
    final String sunTicker = "SUNW";
    final String oracleTicker = "ORCL";
    final String ciscoTicker = "CSCO";
    void valueChanged(String tickerSymbol, double newValue);

The interface shown in Fig. 1 is the StockWatcher interface mentioned previously. This interface defines three constants, which are the ticker symbols of watchable stocks. This interface also declares, but does not implement, the valueChanged method. Classes that implement this interface provide the implementation for that method.

The interface declaration

Fig. 2 shows all possible components of an interface declaration.

Figure 2: The possible components of an interface declaration and their purposes

Two elements are required in an interface declaration -- the interface keyword and the name of the interface. The public access specifier indicates that the interface can be used by any class in any package. If you do not specify that your interface is public, your interface will be accessible only to classes that are defined in the same package as the interface.

An interface declaration can have one other component: a list of superinterfaces. An interface can extend other interfaces, just as a class can extend or subclass another class. However, whereas a class can extend only one other class, an interface can extend any number of interfaces. The list of superinterfaces is a comma-separated list of all the interfaces extended by the new interface.

The interface body

The interface body contains method declarations for all the methods included in the interface. A method declaration within an interface is followed by a semicolon (Wink because an interface does not provide implementations for the methods declared within it. All methods declared in an interface are implicitly public and abstract.

An interface can contain constant declarations in addition to method declarations. All constant values defined in an interface are implicitly public, static, and final.

Member declarations in an interface disallow the use of some declaration modifiers; you cannot use transient, volatile, or synchronized in a member declaration in an interface. Also, you may not use the private and protected specifiers when declaring members of an interface.

Implementing an interface

An interface defines a protocol of behaviour. A class that implements an interface adheres to the protocol defined by that interface. To declare a class that implements an interface, include an implements clause in the class declaration. Your class can implement more than one interface (the Java platform supports multiple inheritance for interfaces), so the implements keyword is followed by a comma-separated list of the interfaces implemented by the class.

By Convention: The implements clause follows the extends clause, if it exists.

Here's a partial example of an applet that implements the StockWatcher interface:


public class StockApplet extends Applet
    implements StockWatcher {
    public void valueChanged(String tickerSymbol, double newValue) {
        if (tickerSymbol.equals(sunTicker)) {
        } else if (tickerSymbol.equals(oracleTicker)) {
        } else if (tickerSymbol.equals(ciscoTicker)) {

Note that this class refers to each constant defined in StockWatcher: sunTicker, oracleTicker, and ciscoTicker, by its simple name. Classes that implement an interface inherit the constants defined within that interface. So those classes can use simple names to refer to the constants. Any other class can use an interfaces constants with a qualified name, like this:


When a class implements an interface, it is essentially signing a contract. Either the class must implement all the methods declared in the interface and its superinterfaces, or the class must be declared abstract. The method signature -- the name and the number and type of arguments in the class -- must match the method signature as it appears in the interface. The StockApplet implements the StockWatcher interface, so the applet provides an implementation for the valueChanged method. The method ostensibly updates the applet's display or otherwise uses this information.

Using an interface as a type

When you define a new interface, you are defining a new reference data type. You can use interface names anywhere you can use any other data type name. Recall that the data type for the first argument to the watchStock method in the StockMonitor class is StockWatcher:


public class StockMonitor {
    public void watchStock(StockWatcher watcher, String tickerSymbol,
        double delta) {

Only an instance of a class that implements the interface can be assigned to a reference variable whose type is an interface name. So only instances of a class that implements the StockWatcher interface can register to be notified of stock value changes. StockWatcher objects are guaranteed to have a valueChanged method.

Warning! Interfaces cannot grow

Suppose that you want to add some functionality to StockWatcher. For instance, suppose that you want to add a method that reports the current stock price, regardless of whether the value changed:


public interface StockWatcher {
    final String sunTicker = "SUNW";
    final String oracleTicker = "ORCL";
    final String ciscoTicker = "CSCO";
    void valueChanged(String tickerSymbol, double newValue);
    void currentValue(String tickerSymbol, double newValue);

However, if you make this change, all classes that implement the old StockWatcher interface will break because they don't implement the interface anymore! Programmers relying on this interface will protest loudly.

Try to anticipate all uses for your interface up front and specify it completely from the beginning. Given that this is often impossible, you may need either to create more interfaces later or to break your customers code. For example, you could create a StockWatcher subinterface called StockTracker that declared the new method:


public interface StockTracker extends StockWatcher {
    void currentValue(String tickerSymbol, double newValue);

Now users of your code can choose to upgrade to the new interface or to stick with the old interface.

Part II continues here...
 Printer Friendly Page  Printer Friendly Page
 Send to a Friend  Send to a Friend

.. Bookmark and Share

Search here again if you need more info!
Custom Search

Home Code Examples Java Forum All Java Tips Books Submit News, Code... Search... Offshore Software Tech Doodling

RSS feed Java FAQ RSS feed Java FAQ News     

    RSS feed Java Forums RSS feed Java Forums

All logos and trademarks in this site are property of their respective owner. The comments are property of their posters, all the rest 1999-2006 by Java FAQs Daily Tips.

Interactive software released under GNU GPL, Code Credits, Privacy Policy