Java Reference
In-Depth Information
«interface»
Edible
Animal
+howToEat(): String
+sound(): String
Fruit
Chicken
Tiger
Orange
Apple
F IGURE 15.4 Edible is a supertype for Chicken and Fruit . Animal is a supertype for
Chicken and Tiger . Fruit is a supertype for Orange and Apple .
signature and return type. The Chicken class implements the howToEat method (lines
22-24). Chicken also extends Animal to implement the sound method (lines 27-29).
The Fruit class implements Edible . Since it does not implement the howToEat method,
Fruit must be denoted as abstract (line 39). The concrete subclasses of Fruit must
implement the howToEat method. The Apple and Orange classes implement the howToEat
method (lines 45, 52).
The main method creates an array with three objects for Tiger , Chicken , and Apple
(line 3), and invokes the howToEat method if the element is edible (line 6) and the sound
method if the element is an animal (line 9).
In essence, the Edible interface defines common behavior for edible objects. All edible
objects have the howToEat method.
common behavior
Note
Since all data fields are public static final and all methods are public
abstract in an interface, Java allows these modifiers to be omitted. Therefore the fol-
lowing interface definitions are equivalent:
omitting modifiers
public interface T {
final int K = 1 ;
public interface T {
int K = 1 ;
public static
Equivalent
void p();
void p();
public abstract
}
}
Tip
A constant defined in an interface can be accessed using the syntax
InterfaceName.CONSTANT_NAME (e.g., T.K ). It is a good practice to define com-
mon constants that are shared by many classes in an interface. For example, the con-
stants LEFT , CENTER , RIGHT , LEADING , TRAILING , TOP , and BOTTOM used in
AbstractButton are also used in many other Swing components. These constants are
centrally defined in the javax.swing.SwingConstants interface. All Swing GUI
components implement SwingConstants . You can reference the constants through
SwingConstants or a GUI component. For example, SwingConstants.CENTER is
the same as JButton.CENTER .
accessing constants
SwingConstants
Check
Point
15.13
Suppose A is an interface. Can you create an instance using new A() ?
 
Search WWH ::




Custom Search