站内搜索: 请输入搜索关键词
当前页面: 在线文档首页 > Java Tutorial 5.0 英文版

Warning! Interfaces Cannot Grow - Java Tutorial 5.0 英文版

The JavaTM Tutorial
Previous Page Lesson Contents Next Page Start of Tutorial > Start of Trail > Start of Lesson Search
Feedback Form

Trail: Learning the Java Language
Lesson: Interfaces and Packages

Warning! Interfaces Cannot Grow

Suppose want to add some functionality to StockWatcher. For instance, assume you want to add a method that reports current stock price, regardless of whether the value has changed.
public interface StockWatcher {
    void valueChanged(TickerSymbol tickerSymbol,
                      BigDecimal newValue); 
    void currentValue(TickerSymbol tickerSymbol,
                      BigDecimal 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 to 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 customer's code. For example, you could create a StockWatcher subinterface called StockTracker to declare the new method.

public interface StockTracker extends StockWatcher {
    void currentValue(TickerSymbol tickerSymbol,
                      BigDecimal newValue);
}
Now users of your code can choose to upgrade to the new interface or to stick with the old interface.

Previous Page Lesson Contents Next Page Start of Tutorial > Start of Trail > Start of Lesson Search
Feedback Form

Copyright 1995-2005 Sun Microsystems, Inc. All rights reserved.