Easy to Learn Java: Programming Articles, Examples and Tips

Start with Java in a few days with Java Lessons or Lectures

Home

Code Examples

Java Tools

More Java Tools!

Java Forum

All Java Tips

Books

Submit News
Search the site here...
Search...
 
Search the JavaFAQ.nu
1000 Java Tips ebook

1000 Java Tips - Click here for the high resolution copy!1000 Java Tips - Click here for the high resolution copy!

Java Screensaver, take it here

Free "1000 Java Tips" eBook is here! It is huge collection of big and small Java programming articles and tips. Please take your copy here.

Take your copy of free "Java Technology Screensaver"!.

Easy Learn Java: Programming Articles, Examples and Tips - Page 489


Previous 1060 Stories (530 Pages, 2 Per Page) Next

Easy Java Lecture 14: Interfaces and packages. Part II. Teach/learn online

Go to all tips in Java Lectures by Anatoliy Malyarenko

Creating and using packages

To make classes easier to find and to use, to avoid naming conflicts, and to control access, programmers bundle groups of related classes and interfaces into packages.

Definition 2. A package is a collection of related classes and interfaces providing access protection and namespace management.

The classes and interfaces that are part of the Java platform are members of various packages that bundle classes by function: fundamental classes are in java.lang, classes for reading and writing (input and output) are in java.io, and so on. You can put your classes and interfaces in packages, too.

Let's look at a set of classes and examine why you might want to put them in a package. Suppose that you write a group of classes that represent a collection of graphic objects, such as circles, rectangles, lines, and points. You also write an interface, Draggable, that classes implement if they can be dragged with the mouse by the user:


Code:

//in the Graphic.java file
public abstract class Graphic {
    . . .
}
//in the Circle.java file
public class Circle extends Graphic implements Draggable {
    . . .
}
//in the Rectangle.java file
public class Rectangle extends Graphic implements Draggable {
    . . .
}
//in the Draggable.java file
public interface Draggable {
    . . .
}

You should bundle these classes and the interface in a package for several reasons:

  • You and other programmers can easily determine that these classes and interfaces are related.
  • You and other programmers know where to find classes and interfaces that provide graphics-related functions.
  • The names of your classes wont conflict with class names in other packages, because the package creates a new namespace.
  • You can allow classes within the package to have unrestricted access to one another yet still restrict access for classes outside the package.

Creating a package

To create a package, you put a class or an interface in it. To do this, you put a package statement at the top of the source file in which the class or the interface is defined. For example, the following code appears in the source file Circle.java and puts the Circle class in the graphics package:

Code:

package graphics;
public class Circle extends Graphic implements Draggable {
    . . .
}

The Circle class is a public member of the graphics package. You must include a package statement at the top of every source file that defines a class or an interface that is to be a member of the graphics package. So you would also include the statement in Rectangle.java and so on:

Code:

package graphics;
public class Rectangle extends Graphic implements Draggable {
    . . .
}

The scope of the package statement is the entire source file, so all classes and interfaces defined in Circle.java and Rectangle.java are also members of the graphics package. If you put multiple classes in a single source file, only one may be public, and it must share the name of the source files base name. Only public package members are accessible from outside the package.

If you do not use a package statement, your class or interface ends up in the default package, which is a package that has no name. Generally speaking, the default package is only for small or temporary applications or when you are just beginning development. Otherwise, classes and interfaces belong in named packages.

Naming a package

With programmers all over the world writing classes and interfaces using the Java programming language, it is likely that two programmers will use the same name for two different classes. In fact, the previous example does just that: It defines a Rectangle class when there is already a Rectangle class in the java.awt package. Yet the compiler allows both classes to have the same name.

Why? Because they are in different packages, and the fully qualified name of each class includes the package name. That is, the fully qualified name of the Rectangle class in the graphics package is graphics.Rectangle, and the fully qualified name of the Rectangle class in the java.awt package is java.awt.Rectangle.

This generally works just fine unless two independent programmers use the same name for their packages. What prevents this problem? Convention.

By Convention: Companies use their reversed Internet domain name in their package names, like this: com.company.package. Some companies now choose to drop the first element com. in this example from their package names.

Name collisions that occur within a single company need to be handled by convention within that company, perhaps by including the region or the project name after the company name, for example, com.company.region.package.

Using package members

Only public package members are accessible outside the package in which they are defined. To use a public package member from outside its package, you must do one or more of the following:

  • Refer to the member by its long (qualified) name.
  • Import the package member.
  • Import the members entire package.

Each is appropriate for different situations.

Referring to a package member by name

So far, the examples have referred to classes and interfaces by their simple names, such as Rectangle and StockWatcher. You can use a package members simple name if the code you are writing is in the same package as that member or if the members package has been imported.

However, if you are trying to use a member from a different package and that package has not been imported, you must use the members qualified name, which includes the package name. This is the qualified name for the Rectangle class declared in the graphics package in the previous example:

graphics.Rectangle

You could use this long name to create an instance of graphics.Rectangle:

Code:
 
    graphics.Rectangle myRect = new graphics.Rectangle();

You'll find that using long names is okay for one-shot uses. But you'd likely get annoyed if you had to write graphics.Rectangle again and again. Also, your code would get very messy and difficult to read. In such cases, you can just import the member instead.

Importing a package member

To import a specific member into the current file, put an import statement at the beginning of your file before any class or interface definitions but after the package statement, if there is one. Here's how you would import the Circle class from the graphics package created earlier:

Code:

    import graphics.Circle;

Now you can refer to the Circle class by its simple name:

Code:

    Circle myCircle = new Circle();

This approach works well if you use just a few members from the graphics package. But if you use many classes and interfaces from a package, you can import the entire package.

Importing an entire package

To import all the classes and interfaces contained in a particular package, use the import statement with the asterisk (*) wildcard character:

Code:

    import graphics.*;

Now you can refer to any class or interface in the graphics package by its short name:

Code:

    Circle myCircle = new Circle();</p>
    Rectangle myRectangle = new Rectangle();

The asterisk in the import statement can be used only to specify all the classes within a package, as shown here. It cannot be used to match a subset of the classes in a package. For example, the following does not match all the classes in the graphics package that begin with A:

Code:

    import graphics.A*; // does not work

Instead, it generates a compiler error. With the import statement, you can import only a single package member or an entire package.

For your convenience, the Java runtime system automatically imports two entire packages:

  • The java.lang package.
  • The current package by default.

Disambiguating a name

If by some chance a member in one package shares the same name with a member in another package and both packages are imported, you must refer to each member by its qualified name. For example, the previous example defined a class named Rectangle in the graphics package. The java.awt package also contains a Rectangle class. If both graphics and java.awt have been imported, the following is ambiguous:

Code:

    Rectangle rect;

In such a situation, you have to be more specific and use the members qualified name to indicate exactly which Rectangle class you want:

Code:

    graphics.Rectangle rect;

Managing source and class files

Many implementations of the Java platform rely on hierarchical file systems to manage source and class files, although The Java Language Specification does not require this. The strategy is as follows.

You put the source code for a class or an interface in a text file whose name is the simple name of the class or the interface and whose extension is .java. Then you put the source file in a directory whose name reflects the name of the package to which the class or the interface belongs. For example, the source code for the Rectangle class would be in a file named Rectangle.java, and the file would be in a directory named graphics.

The graphics directory might be anywhere on the file system. The figure below shows how this works.

The qualified name of the package member and the path name to the file are parallel, assuming the Windows file name separator slash (\):

class name graphics.Rectangle
pathname to file graphics\Rectangle.java

As you may recall, by convention a company uses its reversed Internet domain name in its package names. The fictional company whose Internet domain name is taranis.com would precede all its package names with com.taranis. Each component of the package name corresponds to a subdirectory. So if Taranis had a graphics package that contained a Rectangle.java source file, it would be contained in a series of subdirectories, as shown below.

When you compile a source file, the compiler creates a different output file for each class and interface defined in it. The base name of the output file is the name of the class or the interface, and its extension is .class, as shown in the following figure.

Like a .java file, a .class file should also be in a series of directories that reflect the package name. However, it does not have to be in the same directory as its source. You could arrange your source and class directories separately, as shown below.

By doing this, you can give the classes directory to other programmers without revealing your sources.

Why all the bother about directories and file names? You need to manage your source and class files in this manner so that the compiler and the interpreter can find all the classes and interfaces your program uses. When the compiler encounters a new class as its compiling your program, it must be able to find the class so as to resolve names, do type checking, and so on. Similarly, when the interpreter encounters a new class as its running your program, it must be able to find the class to invoke its methods, and so on. Both the compiler and the interpreter search for classes in each directory or ZIP file listed in your class path.

Definition 3. A class path is an ordered list of directories or ZIP files in which to search for class files.

Each directory listed in the class path is a top-level directory in which package directories appear. From the top-level directory, the compiler and the interpreter can construct the rest of the path, based on the package and the class name for the class. For example, the class path entry for the directory structure shown in the previous diagram would include classes but not com or any of the directories below com. Both the compiler and the interpreter construct the path name to a .class file with its full package name.

By default, the compiler and the interpreter search the current directory and the ZIP file containing the Java platform class files. In other words, the current directory and the Java platform class files are automatically in your class path. Most, if not all, classes can be found in these two locations. So its likely that you don't have to worry about your class path. In some cases, however, you might have to set your class path.


13808 bytes more | comments? | Printer Friendly Page  Send to a Friend | Score: 0
Posted by jalex on Saturday, December 16, 2006 (21:00:00) (6402 reads)

Easy Java Lecture 14: Interfaces and packages. Part I. Teach/learn online

Go to all tips in Java Lectures by Anatoliy Malyarenko

Interfaces and packages

by: Anatoliy Malyarenko

Abstract

  • Contents of the lecture.
  • Creating interfaces.
  • Creating and using packages.

What is an interface?

An interface defines a protocol of behaviour that can be implemented by any class anywhere in the class hierarchy. An interface defines a set of methods but does not implement them. A class that implements the interface agrees to implement all the methods defined in the interface, thereby agreeing to certain behaviour.

Definition 1. An interface is a named collection of method definitions (without implementations). An interface can also declare constants. Because an interface is simply a list of unimplemented, and therefore abstract, methods, you might wonder how an interface differs from an abstract class. The differences are significant.

  • An interface cannot implement any methods, whereas an abstract class can.
  • A class can implement many interfaces but can have only one superclass.
  • An interface is not part of the class hierarchy. Unrelated classes can implement the same interface.

Suppose that you have written a class that can watch stock prices coming over a data feed. This class allows other classes to register to be notified when the value of a particular stock changes. First, your class, which we'll call StockMonitor, would implement a method that lets other objects register for notification:

Code:

public class StockMonitor {
    public void watchStock(StockWatcher watcher,
        String tickerSymbol, double delta) {
        ...
    }
}

The first argument to this method is a StockWatcher object. StockWatcher is the name of an interface whose code you will see later. That interface declares one method: valueChanged. An object that wants to be notified of stock changes must be an instance of a class that implements this interface and thus implements the valueChanged method.

The other two arguments provide the symbol of the stock to watch and the amount of change that the watcher considers interesting enough to be notified of. When the StockMonitor class detects an interesting change, it calls the valueChanged method of the watcher.

The watchStock method ensures, through the data type of its first argument, that all registered objects implement the valueChanged method. It makes sense to use an interface data type here because it matters only that registrants implement a particular method. If StockMonitor had used a class name as the data type, that would artificially force a class relationship on its users. Because a class can have only one superclass, it would also limit what type of objects can use this service. By using an interface, the registered objects class could be anything -- Applet or Thread -- for instance, thus allowing any class anywhere in the class hierarchy to use this service.

Defining an interface

Fig. 1 shows that an interface definition has two components: the interface declaration and the interface body. The interface declaration declares various attributes about the interface, such as its name and whether it extends other interfaces. The interface body contains the constant and the method declarations for that interface.



Figure 1: The StockWatcher interface and the structure of an interface definition

Code:

public interface StockWatcher {
    final String sunTicker = "SUNW";
    final String oracleTicker = "ORCL";
    final String ciscoTicker = "CSCO";
    void valueChanged(String tickerSymbol, double newValue);
}

The interface shown in Fig. 1 is the StockWatcher interface mentioned previously. This interface defines three constants, which are the ticker symbols of watchable stocks. This interface also declares, but does not implement, the valueChanged method. Classes that implement this interface provide the implementation for that method.

The interface declaration

Fig. 2 shows all possible components of an interface declaration.


Figure 2: The possible components of an interface declaration and their purposes

Two elements are required in an interface declaration -- the interface keyword and the name of the interface. The public access specifier indicates that the interface can be used by any class in any package. If you do not specify that your interface is public, your interface will be accessible only to classes that are defined in the same package as the interface.

An interface declaration can have one other component: a list of superinterfaces. An interface can extend other interfaces, just as a class can extend or subclass another class. However, whereas a class can extend only one other class, an interface can extend any number of interfaces. The list of superinterfaces is a comma-separated list of all the interfaces extended by the new interface.

The interface body

The interface body contains method declarations for all the methods included in the interface. A method declaration within an interface is followed by a semicolon (Wink because an interface does not provide implementations for the methods declared within it. All methods declared in an interface are implicitly public and abstract.

An interface can contain constant declarations in addition to method declarations. All constant values defined in an interface are implicitly public, static, and final.

Member declarations in an interface disallow the use of some declaration modifiers; you cannot use transient, volatile, or synchronized in a member declaration in an interface. Also, you may not use the private and protected specifiers when declaring members of an interface.

Implementing an interface

An interface defines a protocol of behaviour. A class that implements an interface adheres to the protocol defined by that interface. To declare a class that implements an interface, include an implements clause in the class declaration. Your class can implement more than one interface (the Java platform supports multiple inheritance for interfaces), so the implements keyword is followed by a comma-separated list of the interfaces implemented by the class.

By Convention: The implements clause follows the extends clause, if it exists.

Here's a partial example of an applet that implements the StockWatcher interface:

Code:

public class StockApplet extends Applet
    implements StockWatcher {
    ...
    public void valueChanged(String tickerSymbol, double newValue) {
        if (tickerSymbol.equals(sunTicker)) {
            ...
        } else if (tickerSymbol.equals(oracleTicker)) {
            ...
        } else if (tickerSymbol.equals(ciscoTicker)) {
            ...
        }
    }
}

Note that this class refers to each constant defined in StockWatcher: sunTicker, oracleTicker, and ciscoTicker, by its simple name. Classes that implement an interface inherit the constants defined within that interface. So those classes can use simple names to refer to the constants. Any other class can use an interfaces constants with a qualified name, like this:

StockWatcher.sunTicker

When a class implements an interface, it is essentially signing a contract. Either the class must implement all the methods declared in the interface and its superinterfaces, or the class must be declared abstract. The method signature -- the name and the number and type of arguments in the class -- must match the method signature as it appears in the interface. The StockApplet implements the StockWatcher interface, so the applet provides an implementation for the valueChanged method. The method ostensibly updates the applet's display or otherwise uses this information.

Using an interface as a type

When you define a new interface, you are defining a new reference data type. You can use interface names anywhere you can use any other data type name. Recall that the data type for the first argument to the watchStock method in the StockMonitor class is StockWatcher:

Code:

public class StockMonitor {
    public void watchStock(StockWatcher watcher, String tickerSymbol,
        double delta) {
        ...
    }
}

Only an instance of a class that implements the interface can be assigned to a reference variable whose type is an interface name. So only instances of a class that implements the StockWatcher interface can register to be notified of stock value changes. StockWatcher objects are guaranteed to have a valueChanged method.

Warning! Interfaces cannot grow

Suppose that you want to add some functionality to StockWatcher. For instance, suppose that you want to add a method that reports the current stock price, regardless of whether the value changed:

Code:

public interface StockWatcher {
    final String sunTicker = "SUNW";
    final String oracleTicker = "ORCL";
    final String ciscoTicker = "CSCO";
    void valueChanged(String tickerSymbol, double newValue);
    void currentValue(String tickerSymbol, double newValue);
}

However, if you make this change, all classes that implement the old StockWatcher interface will break because they don't implement the interface anymore! Programmers relying on this interface will protest loudly.

Try to anticipate all uses for your interface up front and specify it completely from the beginning. Given that this is often impossible, you may need either to create more interfaces later or to break your customers code. For example, you could create a StockWatcher subinterface called StockTracker that declared the new method:

Code:

public interface StockTracker extends StockWatcher {
    void currentValue(String tickerSymbol, double newValue);
}

Now users of your code can choose to upgrade to the new interface or to stick with the old interface.

Part II continues here...
10456 bytes more | comments? | Printer Friendly Page  Send to a Friend | Score: 0
Posted by jalex on Thursday, December 14, 2006 (21:26:39) (4762 reads)

Previous 1060 Stories (530 Pages, 2 Per Page) Next

530| 529| 528| 527| 526| 525| 524| 523| 522| 521| 520| 519| 518| 517| 516| 515| 514| 513| 512| 511| 510| 509| 508| 507| 506| 505| 504| 503| 502| 501| 500| 499| 498| 497| 496| 495| 494| 493| 492| 491| 490|
489
| 488| 487| 486| 485| 484| 483| 482| 481| 480| 479| 478| 477| 476| 475| 474| 473| 472| 471| 470| 469| 468| 467| 466| 465| 464| 463| 462| 461| 460| 459| 458| 457| 456| 455| 454| 453| 452| 451| 450| 449| 448| 447| 446| 445| 444| 443| 442| 441| 440| 439| 438| 437| 436| 435| 434| 433| 432| 431| 430| 429| 428| 427| 426| 425| 424| 423| 422| 421| 420| 419| 418| 417| 416| 415| 414| 413| 412| 411| 410| 409| 408| 407| 406| 405| 404| 403| 402| 401| 400| 399| 398| 397| 396| 395| 394| 393| 392| 391| 390| 389| 388| 387| 386| 385| 384| 383| 382| 381| 380| 379| 378| 377| 376| 375| 374| 373| 372| 371| 370| 369| 368| 367| 366| 365| 364| 363| 362| 361| 360| 359| 358| 357| 356| 355| 354| 353| 352| 351| 350| 349| 348| 347| 346| 345| 344| 343| 342| 341| 340| 339| 338| 337| 336| 335| 334| 333| 332| 331| 330| 329| 328| 327| 326| 325| 324| 323| 322| 321| 320| 319| 318| 317| 316| 315| 314| 313| 312| 311| 310| 309| 308| 307| 306| 305| 304| 303| 302| 301| 300| 299| 298| 297| 296| 295| 294| 293| 292| 291| 290| 289| 288| 287| 286| 285| 284| 283| 282| 281| 280| 279| 278| 277| 276| 275| 274| 273| 272| 271| 270| 269| 268| 267| 266| 265| 264| 263| 262| 261| 260| 259| 258| 257| 256| 255| 254| 253| 252| 251| 250| 249| 248| 247| 246| 245| 244| 243| 242| 241| 240| 239| 238| 237| 236| 235| 234| 233| 232| 231| 230| 229| 228| 227| 226| 225| 224| 223| 222| 221| 220| 219| 218| 217| 216| 215| 214| 213| 212| 211| 210| 209| 208| 207| 206| 205| 204| 203| 202| 201| 200| 199| 198| 197| 196| 195| 194| 193| 192| 191| 190| 189| 188| 187| 186| 185| 184| 183| 182| 181| 180| 179| 178| 177| 176| 175| 174| 173| 172| 171| 170| 169| 168| 167| 166| 165| 164| 163| 162| 161| 160| 159| 158| 157| 156| 155| 154| 153| 152| 151| 150| 149| 148| 147| 146| 145| 144| 143| 142| 141| 140| 139| 138| 137| 136| 135| 134| 133| 132| 131| 130| 129| 128| 127| 126| 125| 124| 123| 122| 121| 120| 119| 118| 117| 116| 115| 114| 113| 112| 111| 110| 109| 108| 107| 106| 105| 104| 103| 102| 101| 100| 99| 98| 97| 96| 95| 94| 93| 92| 91| 90| 89| 88| 87| 86| 85| 84| 83| 82| 81| 80| 79| 78| 77| 76| 75| 74| 73| 72| 71| 70| 69| 68| 67| 66| 65| 64| 63| 62| 61| 60| 59| 58| 57| 56| 55| 54| 53| 52| 51| 50| 49| 48| 47| 46| 45| 44| 43| 42| 41| 40| 39| 38| 37| 36| 35| 34| 33| 32| 31| 30| 29| 28| 27| 26| 25| 24| 23| 22| 21| 20| 19| 18| 17| 16| 15| 14| 13| 12| 11| 10| 9| 8| 7| 6| 5| 4| 3| 2| 1|


Home Code Examples Java Forum All Java Tips Books Submit News, Code... Search... Offshore Software Tech Doodling

RSS feed Java FAQ RSS feed Java FAQ News     

    RSS feed Java Forums RSS feed Java Forums

All logos and trademarks in this site are property of their respective owner. The comments are property of their posters, all the rest 1999-2006 by Java FAQs Daily Tips.

Interactive software released under GNU GPL, Code Credits, Privacy Policy