Creating and Using Interfaces and Packages

Team-Fly

Interfaces and packages control how classes are declared and interact with each other. Usually, in object-oriented programming the class hierarchy controls this type of behavior. However, this approach is restrictive because to enjoy the advantages of the class hierarchy, such as inheritance, a class must become part of the hierarchy, which can cause problems with access to variables. Java has extended the functionality of the class hierarchy through interfaces and packages.

Defining an Interface

An interface can be thought of as a template that a class can use in its declaration of methods and constants. An interface is a group of method declarations (with no code) and the constants that a class may adopt. Unlike the class hierarchy, no further link exists between classes that use the same interface.

As the following example shows, the declaration of an interface is similar to that of a class.

interface CommonStuff {     int maxentries = 100;     void printvar();     void addvars(); } 

The rules for interface declaration are as follows:

  • All variables declared within an interface are assumed to be static and final. (Basically, they are constants.)

  • Though an interface can extend another interface (in a fashion similar to the way classes can extend other classes), an interface cannot implement other interfaces.

  • All methods declared within an interface default to abstract and public.

  • Interfaces cannot be used to declare class methods, instance variables, or constructor methods.

Implementing an Interface

Interfaces are implemented within a class, as shown in the following code:

interface CommonStuff {     int maxentries = 100;     void printvar(); } class Test15 implements CommonStuff {     int x;     void printvar()     {         System.out.println("Maxentries = " + maxentries);     } }

Interfaces can also be implemented as a data type, as shown here (with the same interface declaration as above):

class Test16 {     CommonStuff obj1; }

Creating and Using Packages

A package allows you to link several classes or interfaces without using the class hierarchy system. Packages are generally used to provide access control to the members of the class.

Packages are implemented by using the keyword package before the declaration of the class or interface.

package testpackage; class Test17 { } class Test18 { }


Team-Fly


Java & BAPI Technology for SAP
Java & BAPI Technology for SAP
ISBN: 761523057
EAN: N/A
Year: 1998
Pages: 199

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net