Java Reference
In-Depth Information
This same property allows you to import predefined classes and packages from other projects or
even from other developers. The import statements you've used already in some of the exercises
are an example of this. When you started using BigDecimal , instead of doubles, to provide more
control over rounding of decimal point numbers, you used the following statement at the top of
your class: import java.math.BigDecimal; to import the BigDecimal class from Java's math
package.
In order for a program to identify a package by name, the program should be executed from
the directory that contains the package, or the CLASSPATH must include the path to the package.
The CLASSPATH tells the Java Virtual Machine where to find classes and packages when
needed.
interfaces
An interface defines a protocol, or contract, of behavior. It resembles something like a template
for a class, as it specifies what a class must do, but not how to do it. Instead of a public class
ClassName heading, you should use the public interface InterfaceName heading. Interfaces
contain headings for public methods without implementations. These are the same as abstract meth-
ods discussed earlier in the chapter, but because methods in interfaces are necessarily abstract, there
is no need to use the abstract keyword in an interface. Comments should be provided with meth-
ods to make it clear what the method is intended for, especially since there is no implementation
to read.
Interfaces must have either the public access modifier or no access modifier, indicating they are
only accessible within the same package. An interface may have variables only if they are final ,
static , and initialized with a constant value.
Similar to a subclass extending a superclass, a class can implement an interface. If a class imple-
ments an interface, it must implement all methods defined in the interface. While a subclass can only
extend one superclass, a single class can implement any number of interfaces. Because the methods
in interfaces are unimplemented, there is no risk of ambiguity, and the class will have one single
implementation for each method. Methods in an interface are implicitly assumed to be public, so the
public access modifier is not necessary for interface methods.
Interfaces can extend one or more other interfaces. Any class implementing an interface must imple-
ment all methods in the interface itself, as well as any interfaces it extends.
Polymorphism applies to interfaces similar to superclasses. If the Shape class implements an inter-
face Measurable , then you could have a variable of type Measurable referencing a Rectangle
object or a variable of type Shape referencing a Circle object. Consider the following Measurable
interface for an example of interface syntax.
/**
* An interface for measuring methods.
*/
public interface Measurable{
/** Returns the perimeter of an object */
double calculatePerimeter();
 
 
Search WWH ::




Custom Search