Page 568 - Introduction to Programming with Java: A Problem Solving Approach
P. 568
534 Chapter 13 Inheritance and Polymorphism
implement the same Java interface. In our accounting system example, the interface for the “get” methods that access originalCost, acquisitionDate, and depreciationRate instance variables might be called the AssetAging interface. The AssetAging interface would contain declarations/headings for its methods, but not definitions.
If a particular class includes a definition of all of the methods declared in some interface (like AssetAging), you can tell the world (and the Java compiler) that that class provides such definitions by appending an implements clause to its class heading, like this:
public<class-name> implements<interface-name> {
...
For multiple interfaces, separate their names with commas, like this:
public<class-name> implements<interface-name1>, <interface-name2>, ... {
...
For inheritance and an interface, do it like this:
public<class-name> extends<parent-class-name> implements<interface-name> {
...
A given class can extend only one superclass, but it can implement any number of interfaces. A Java interface is like a “pure” abstrAacptaclagss.oIt’s pPurDe iFn thatEitnehveradenfinceseanry methods. It’s less versatile than an abstract class, however. It can’t declare any static methods, it can’t declare any variables, anditcan’tdeclareanyinstanceconstants.Inotherwords,itprovidesonlypublic static final namedconstantsandonlypublic abstractmethoddeclarations.Here’sthesyntaxforaninterface definition:
interface <interface-name> {
<type> <CONSTANT_NAME> = <value>;
...
<return-type> <method-name>(<type> <parameter-name> ...); ...
}
You begin the definition of an interface with the keyword, interface, just like you begin the defi- nition of a class with the keyword, class. You define named constants in an interface the same way you define named constants in a class, and you declare methods in an interface by appending a semicolon to the method headings. Note that the keyword public does not appear anywhere in our syntax template. You may include the public modifier, but it’s not necessary, and it’s standard practice to omit it, since it simply does not make sense for an interface or any of its components to be anything but public. Also note that the keyword abstract does not appear anywhere in our syntax template. You may include an abstract modifier in any method declaration, and you may include the abstract modifier in the interface head- ing, but again, it’s not necessary, and it’s standard practice to omit it, since it simply does not make sense to have an interface that is not completely abstract. Also note that the keyword static does not appear anywhere in our syntax template. It’s understood that any constant is static, and it’s understood that any