Interfaces and Packages

What it we really do need multiple inheritance?

Interface

Is a special kind of class which defines a specification of a set of methods. Provides a guarantee that any class that implements this interface will provide these methods. Is similar to setting «standards» and any class implementing it will get a «stamp of approval».

Inheritance vs. interfaces

Interfaces are different from inheritance since interfaces do not inherit state or behavior, instead they just define a specification.

Syntax

interface interfaceName {
     /* Method specifications */
}

class className implements interfaceName {
     /* Bodies for the interface methods */
     /* Own data and methods. */
}

Example

interface MovableObject {
   boolean start();
   void stop();
   boolean turn(int degrees);
   double fuelRemaining();
   boolean changeSpeed(double kmPerHour);
}

class Plane implements MovableObject {
    boolean start() {
    //Do what's necessary to start the plane. Return true if it actually started.
    }
    void stop() {
    //Do whatever is necessary to stop the plane.
    }
    boolean turn(int degrees) {
    // Do what's necessary to turn the plane. Return true if it worked.
    }
    double fuelRemaining() {
    //Return the amount of plane fuel remaining.
    }
    boolean changeSpeed(double kmPerHour) {
    //Do what's necessary to accelerate or decelerate by the given amount
    }
}

Packages

In Java package is a collection of classes. May or may not be related by inheritance. Groups similar and interdependent classes together. The Java API is composed of multiple packages.

The import statement is used to assert that a particular program will use classes from a particular package.

The classes must be organized in the directory structure such that they can be found when referenced by an import statement.

There is a CLASSPATH environment variable on each computer system that determines where to look for classes when referenced.

The import statement specifies particular classes, or an entire package of classes, that can be used in that program. Import statements are not necessary; a class can always be referenced by its fully qualified name in-line. If two classes from two packages have the same name and are used in the same program, they must be referenced by their fully qualified name.

If you will use only one class from a package, import that class specifically. If two or more classes will be used, use the * wildcard character in the import statement to provide access to all classes in the package.

 
abstract_data_types_and_algorithms/interfaces.txt · Последние изменения: 2009/09/10 05:45 От freetonik
 
За исключением случаев, когда указано иное, содержимое этой вики предоставляется на условиях следующей лицензии:CC Attribution-Noncommercial-Share Alike 3.0 Unported
Recent changes RSS feed Donate Powered by PHP Valid XHTML 1.0 Valid CSS Driven by DokuWiki