Вы находитесь на странице: 1из 35

Defining Methods

Here is an example of a typical method declaration: public double calculateAnswer(double wingSpan, int numberOfEngines, double length, double grossTons) { //do the calculation here } The only required elements of a method declaration are the method's return type, name, a pair of parentheses, (), and a body between braces, {}. More generally, method declarations have six components, in order: 1.Modifiers such as public, private, and others you will learn about later. 2.The return type the data type of the value returned by the method, or void if the method does not return a value. 3.The method name the rules for field names apply to method names as well, but the convention is a little different. 4.The parameter list in parenthesis a comma-delimited list of input parameters, preceded by their data types, enclosed by parentheses, (). If there are no parameters, you must use empty parentheses. The method body, enclosed between braces the method's code, including the declaration of local variables, goes here. Definition: Two of the components of a method declaration comprise the method signature the method's name and the parameter types. The signature of the method declared above is: calculateAnswer(double, int, double, double) Naming a Method Although a method name can be any legal identifier, code conventions restrict method names. By convention, method names should be a verb in lowercase or a multi-word name that begins with a verb in lowercase, followed by adjectives, nouns, etc. In multi-word names, the first letter of each of the second and following words should be capitalized. Here are some examples: run

runFast getBackground getFinalData compareTo setX isEmpty Typically, a method has a unique name within its class. However, a method might have the same name as other methods due to method overloading.

Overloading Methods

The Java programming language supports overloading methods, and Java can distinguish between methods with different method signatures. This means that methods within a class can have the same name if they have different parameter lists (there are some qualifications to this that will be discussed in the lesson titled "Interfaces and Inheritance").

Suppose that you have a class that can use calligraphy to draw various types of data (strings, integers, and so on) and that contains a method for drawing each data type. It is cumbersome to use a new name for each method for example, drawString, drawInteger, drawFloat, and so on. In the Java programming language, you can use the same name for all the drawing methods but pass a different argument list to each method. Thus, the data drawing class might declare four methods named draw, each of which has a different parameter list. public class DataArtist { ... public void draw(String s) { ... } public void draw(int i) { ...

} public void draw(double f) { ... } public void draw(int i, double f) { ... } } Overloaded methods are differentiated by the number and the type of the arguments passed into the method. In the code sample, draw(String s) and draw(int i) are distinct and unique methods because they require different argument types.

You cannot declare more than one method with the same name and the same number and type of arguments, because the compiler cannot tell them apart.

The compiler does not consider return type when differentiating methods, so you cannot declare two methods with the same signature even if they have a different return type.

4.2.2 Access Specifiers

One of the techniques in object-oriented programming is encapsulation. It concerns the hiding of data in a class and making this class available only through methods. In this way the chance of making accidental mistakes in changing values is minimized. Java allows you to control access to classes, methods, and fields via so-called access specifiers.

Java offers four access specifiers, listed below in decreasing accessibility: public protected default (no specifier)

private We look at these access specifiers in more detail. public public classes, methods, and fields can be accessed from everywhere. The only constraint is that a file with Java source code can only contain one public class whose name must also match with the filename. If it exists, this public class represents the application or the applet, in which case the public keyword is necessary to enable your Web browser or appletviewer to show the applet. You use public classes, methods, or fields only if you explicitly want to offer access to these entities and if this access cannot do any harm. An example of a square determined by the position of its upper-left corner and its size: public class Square { // public class public x, y, size; // public instance variables } protected protected methods and fields can only be accessed within the same class to which the methods and fields belong, within its subclasses, and within classes of the same package, but not from anywhere else. You use the protected access level when it is appropriate for a class's subclasses to have access to the method or field, but not for unrelated classes. default (no specifier) If you do not set access to specific level, then such a class, method, or field will be accessible from inside the same package to which the class, method, or field belongs, but not from outside this package. This access-level is convenient if you are creating packages. For example, a geometry package that contains Square and Tiling classes, may be easier and cleaner to implement if the coordinates of the upper-left corner of a Square are directly available to the Tiling class but not outside the geometry package. private private methods and fields can only be accessed within the same class to which the methods and fields belong. private methods and fields are not visible within subclasses and are not inherited by subclasses. So, the private access specifier is opposite to the public access specifier. It is mostly used for encapsulation: data are hidden within the class and accessor methods are provided. An example, in which the position of the upper-left corner of a square can be set or obtained by accessor methods, but individual coordinates are not accessible to the user. public class Square { // public class private double x, y // private (encapsulated) instance variables

public setCorner(int x, int y) { // setting values of private fields this.x = x; this.y = y; }

public getCorner() { // setting values of private fields return Point(x, y); } } Summary of Access Specifiers The following table summarizes the access level permitted by each specifier. Situation public protected default private

Accessible to class from same package? Accessible to class from different package? yes no, unless it is a subclass no no yes yes yes no

Note the difference between the default access which is in fact more restricted than the protected access. Without access specifier (the default choice), methods and variables are accessible only within the class that defines them and within classes that are part of the same package. They are not visible to subclasses unless these are in the same package. protected methods and variables are visible to subclasses regardless of which package they are in.

Arrays

An array is a container object that holds a fixed number of values of a single type. The length of an array is established when the array is created. After creation, its length is fixed. You've seen an example of arrays already, in the main method of the "Hello World!" application. This section discusses arrays in greater detail.

An array of ten elements

Each item in an array is called an element, and each element is accessed by its numerical index. As shown in the above illustration, numbering begins with 0. The 9th element, for example, would therefore be accessed at index 8.

The following program, ArrayDemo, creates an array of integers, puts some values in it, and prints each value to standard output.

class ArrayDemo { public static void main(String[] args) { int[] anArray; // declares an array of integers

anArray = new int[10];

// allocates memory for 10 integers

anArray[0] = 100; // initialize first element anArray[1] = 200; // initialize second element anArray[2] = 300; // etc. anArray[3] = 400; anArray[4] = 500;

anArray[5] = 600; anArray[6] = 700; anArray[7] = 800; anArray[8] = 900; anArray[9] = 1000;

System.out.println("Element at index 0: " + anArray[0]); System.out.println("Element at index 1: " + anArray[1]); System.out.println("Element at index 2: " + anArray[2]); System.out.println("Element at index 3: " + anArray[3]); System.out.println("Element at index 4: " + anArray[4]); System.out.println("Element at index 5: " + anArray[5]); System.out.println("Element at index 6: " + anArray[6]); System.out.println("Element at index 7: " + anArray[7]); System.out.println("Element at index 8: " + anArray[8]); System.out.println("Element at index 9: " + anArray[9]); } } The output from this program is: Element at index 0: 100 Element at index 1: 200 Element at index 2: 300 Element at index 3: 400 Element at index 4: 500 Element at index 5: 600

Element at index 6: 700 Element at index 7: 800 Element at index 8: 900 Element at index 9: 1000

In a real-world programming situation, you'd probably use one of the supported looping constructs to iterate through each element of the array, rather than write each line individually as shown above. However, this example clearly illustrates the array syntax. You'll learn about the various looping constructs (for, while, and do-while) in the Control Flow section. Declaring a Variable to Refer to an Array The above program declares anArray with the following line of code: int[] anArray; // declares an array of integers

Like declarations for variables of other types, an array declaration has two components: the array's type and the array's name. An array's type is written as type[], where type is the data type of the contained elements; the square brackets are special symbols indicating that this variable holds an array. The size of the array is not part of its type (which is why the brackets are empty). An array's name can be anything you want, provided that it follows the rules and conventions as previously discussed in the naming section. As with variables of other types, the declaration does not actually create an array it simply tells the compiler that this variable will hold an array of the specified type.

Similarly, you can declare arrays of other types: byte[] anArrayOfBytes; short[] anArrayOfShorts; long[] anArrayOfLongs; float[] anArrayOfFloats; double[] anArrayOfDoubles; boolean[] anArrayOfBooleans; char[] anArrayOfChars;

String[] anArrayOfStrings;

You can also place the square brackets after the array's name: float anArrayOfFloats[]; // this form is discouraged However, convention discourages this form; the brackets identify the array type and should appear with the type designation.

Creating, Initializing, and Accessing an Array One way to create an array is with the new operator. The next statement in the ArrayDemo program allocates an array with enough memory for ten integer elements and assigns the array to the anArray variable. anArray = new int[10]; // create an array of integers If this statement were missing, the compiler would print an error like the following, and compilation would fail: ArrayDemo.java:4: Variable anArray may not have been initialized. The next few lines assign values to each element of the array: anArray[0] = 100; // initialize first element anArray[1] = 200; // initialize second element anArray[2] = 300; // etc. Each array element is accessed by its numerical index: System.out.println("Element 1 at index 0: " + anArray[0]); System.out.println("Element 2 at index 1: " + anArray[1]); System.out.println("Element 3 at index 2: " + anArray[2]); Alternatively, you can use the shortcut syntax to create and initialize an array: int[] anArray = {100, 200, 300, 400, 500, 600, 700, 800, 900, 1000}; Here the length of the array is determined by the number of values provided between { and }.

You can also declare an array of arrays (also known as a multidimensional array) by using two or more sets of square brackets, such as String[][] names. Each element, therefore, must be accessed by a corresponding number of index values.

In the Java programming language, a multidimensional array is simply an array whose components are themselves arrays. This is unlike arrays in C or Fortran. A consequence of this is that the rows are allowed to vary in length, as shown in the following MultiDimArrayDemo program: class MultiDimArrayDemo { public static void main(String[] args) { String[][] names = {{"Mr. ", "Mrs. ", "Ms. "}, {"Smith", "Jones"}}; System.out.println(names[0][0] + names[1][0]); //Mr. Smith System.out.println(names[0][2] + names[1][1]); //Ms. Jones } } The output from this program is: Mr. Smith Ms. Jones

Finally, you can use the built-in length property to determine the size of any array. The code System.out.println(anArray.length); will print the array's size to standard output. Copying Arrays The System class has an arraycopy method that you can use to efficiently copy data from one array into another: public static void arraycopy(Object src, int srcPos,

Object dest, int destPos, int length) The two Object arguments specify the array to copy from and the array to copy to. The three int arguments specify the starting position in the source array, the starting position in the destination array, and the number of array elements to copy.

The following program, ArrayCopyDemo, declares an array of char elements, spelling the word "decaffeinated". It uses arraycopy to copy a subsequence of array components into a second array:

class ArrayCopyDemo { public static void main(String[] args) { char[] copyFrom = { 'd', 'e', 'c', 'a', 'f', 'f', 'e', 'i', 'n', 'a', 't', 'e', 'd' }; char[] copyTo = new char[7];

System.arraycopy(copyFrom, 2, copyTo, 0, 7); System.out.println(new String(copyTo)); } }

The output from this program is: Caffeine

Strings
Strings, which are widely used in Java programming, are a sequence of characters. In the Java programming language, strings are objects.

The Java platform provides the String class to create and manipulate strings. Creating Strings The most direct way to create a string is to write: String greeting = "Hello world!"; In this case, "Hello world!" is a string literal ;a series of characters in your code that is enclosed in double quotes. Whenever it encounters a string literal in your code, the compiler creates a String object with its value in this case, Hello world!.

As with any other object, you can create String objects by using the new keyword and a constructor. The String class has thirteen constructors that allow you to provide the initial value of the string using different sources, such as an array of characters: char[] helloArray = { 'h', 'e', 'l', 'l', 'o', '.'}; String helloString = new String(helloArray); System.out.println(helloString); The last line of this code snippet displays hello.

Note : The String class is immutable, so that once it is created a String object cannot be changed. The String class has a number of methods, some of which will be discussed below, that appear to modify strings. Since strings are immutable, what these methods really do is create and return a new string that contains the result of the operation. String Length Methods used to obtain information about an object are known as accessor methods. One accessor method that you can use with strings is the length() method, which returns the number of characters contained in the string object. After the following two lines of code have been executed, len equals 17: String palindrome = "Dot saw I was Tod"; int len = palindrome.length(); A palindrome is a word or sentence that is symmetric it is spelled the same forward and backward, ignoring case and punctuation. Here is a short and inefficient program to reverse a palindrome string. It invokes the String method charAt(i), which returns the ith character in the string, counting from 0.

public class StringDemo { public static void main(String[] args) { String palindrome = "Dot saw I was Tod"; int len = palindrome.length(); char[] tempCharArray = new char[len]; char[] charArray = new char[len];

// put original string in an array of chars for (int i = 0; i < len; i++) { tempCharArray[i] = palindrome.charAt(i); }

// reverse array of chars for (int j = 0; j < len; j++) { charArray[j] = tempCharArray[len - 1 - j]; }

String reversePalindrome = new String(charArray); System.out.println(reversePalindrome); } } Running the program produces this output: doT saw I was toD To accomplish the string reversal, the program had to convert the string to an array of characters (first for loop), reverse the array into a second array (second for loop), and then convert back to a string. The String class includes a method, getChars(), to convert a string, or a portion of a string, into an array of characters so we could replace the first for loop in the program above with

palindrome.getChars(0, len, tempCharArray, 0); Concatenating Strings The String class includes a method for concatenating two strings: string1.concat(string2); This returns a new string that is string1 with string2 added to it at the end.

You can also use the concat() method with string literals, as in: "My name is ".concat("Rumplestiltskin"); Strings are more commonly concatenated with the + operator, as in "Hello," + " world" + "!" which results in "Hello, world!" The + operator is widely used in print statements. For example: String string1 = "saw I was "; System.out.println("Dot " + string1 + "Tod"); which prints Dot saw I was Tod Such a concatenation can be a mixture of any objects. For each object that is not a String, its toString() method is called to convert it to a String. Note : The Java programming language does not permit literal strings to span lines in source files, so you must use the + concatenation operator at the end of each line in a multi-line string. For example, String quote = "Now is the time for all good " + "men to come to the aid of their country."; Breaking strings between lines using the + concatenation operator is, once again, very common in print statements. Creating Format Strings

You have seen the use of the printf() and format() methods to print output with formatted numbers. The String class has an equivalent class method, format(), that returns a String object rather than a PrintStream object.

Using String's static format() method allows you to create a formatted string that you can reuse, as opposed to a one-time print statement. For example, instead of System.out.printf("The value of the float variable is %f, while the value of the " + "integer variable is %d, and the string is %s", floatVar, intVar, stringVar); you can write String fs; fs = String.format("The value of the float variable is %f, while the value of the " + "integer variable is %d, and the string is %s", floatVar, intVar, stringVar); System.out.println(fs);

Static Members: Static Methods and Static Variables

Why do we need Static members?

There are situations in which the method s behaviour does not depend on the state of an object. So, there will be no use of having an object when the method itself will not be instance specific.

Let us consider another situation where in we want to keep a count of all the instances instantiated from a particular class. Suppose we declare an instance variable to do the job, it won t work. Its because the instance variables are initialised back to their default value each time a instance is created. So we need some varaible which will be independent of the instances created.

The answer to both the situations is to use the static modifiers, in other words static members.

What exactly are Static Variable and Methods?

Variables and methods marked static belong to the class rather than to any particular instance of the class. These can be used without having any instances of that class at all. Only the class is sufficient to invoke a static method or access a static variable. A static variable is shared by all the instances of that class i.e only one copy of the static variable is maintained.

class Animal {

static int animalCount=0; public Animal() {

animalCount+=1;

} public static void main(String[] args) {

new Animal(); new Animal(); new Animal(); System.out.println( The Number of Animals is: + animalCount);

The output is

The Number of Animals is 3 .

A static method cannot access non-static/instance variables, because a static method is never associated with any instance. The same applies with the non-static methods as well, a static method can t directly invoke a non-static method. But static method can access non-static methods by means of declaring instances and using them.

Note: One of the mistakes most often made by new Java programmers is accessing instance variables from main() method.

How to go about Accessing them?

In case of instance methods and instance variables, instances of that class are used to access them.

<objectReference>.<instanceVariable> <objectReference>.<instanceMethod>

But static members are not associated with any instances. So there is no point in using the object. So, the way static methods (or static variables) are accessed is by using the dot operator on the class name, as opposed to using it on a reference to an instance.

class Animal {

static int animalCount=0;

public Animal() {

animalCount+=1;

} public static int getCount() {

return animalCount;

class TestAnimal {

public static void main(String[] args) {

new Animal(); new Animal(); new Animal(); System.out.println( The Number of Animals is: + Animal.getCount());

/* Notice the way in which the Static method is called using the class name followed by static method. */

Remember that static methods can t be overridden. They can be redefined in a subclass, but redifining and overriding aren t the same thing. Its called as Hiding.

Javadoc Comments

Javadoc Comments are specific to the Java language and provide a means for a programmer to fully document his / her source code as well as providing a means to generate an Application Programmer Interface (API) for the code using the javadoc tool that is bundled with the JDK. These comments have a special format which we will discuss in this section and then in the following section we will look at how to use the javadoc tool to generate an API. The Format of Javadoc Comments

A Javadoc comment precedes any class, interface, method or field declaration and is similar to a multiline comment except that it starts with a forward slash followed by two atserisks (/**). The basic format is a description followed by any number of predefined tags. The entrie comment is indented to align with the source code directly beneath it and it may contain any valid HTML. Generally paragraphs should be separated or designated with the <p> tag. As an example consider: /** * A Container is an object that contains other objects. * @author Trevor Miller * @version 1.2 * @since 0.3

*/ public abstract class Container {

/** * Create an empty container. */ protected Container() { }

/** * Return the number of elements contained in this container. * @return The number of objects contained */ public abstract int count();

/** * Clear all elements from this container. * This removes all contained objects. */ public abstract void clear();

/** * Accept the given visitor to visit all objects contained. * @param visitor The visitor to accept */ public abstract void accept(final Visitor visitor);

/** * Return an iterator over all objects conatined. * @return An iterator over all objects */ public abstract Iterator iterator();

/** * Determine whether this container is empty or not. * @return <CODE>true</CODE> if the container is empty: * <CODE>count == 0</CODE>, <CODE>false</CODE> * otherwise */ public boolean isEmpty() { return (this.count() == 0); }

/** * Determine whether this container is full. * @return <CODE>true</CODE> if conatiner is full, * <CODE>false</CODE> otherwise */ public boolean isFull() { return false; }

We will now discuss the descriptions of a Javadoc comment first before looking at the different tags and their uses. Descriptions

The description should give a concise summary of the item being commented. It should be written in simple and clear English using correct spelling and grammar. Punctuation is required. There are some important style guidelines to bear in mind: The first sentence

The first sentence of the description is the most important part of the entire description. It should be a short and concise summary of the item being commented. This is due to the fact that the Javadoc tool copies the first sentence to the appropriate class or package summary page, which implies that the first sentence should be compact and can stand on its own.

Take a look at the example above again and you'll see that the first sentence is a brief descriptive summary of each item. The use of the <code> tag

The use of the <code> tag is greatly encouraged and should be used for all Java keywords, names and code samples. you'll notice this in the comments of the last two methods of the class in the example above. Omission of parenthesis

When referring to a method that has no parameters or a method which has multiple forms (method overloading) it is acceptable and even encouraged to simply omit the parenthesis. Consider the following example:

The <code>add</code> method inserts items into the vector.

This is the correct way of doing it as opposed to the incorrect way in the next example: The <code>add()</code> method inserts items into the vector.

Method descriptions begin with a verb

A method usually defines a certain behaviour or operation; because of this it usually signals an action that is best described by a verb. Determine whether this container is empty or not.

As opposed to: This method is used to determine whether this container is empty or not.

Avoid abbreviation

One final word on style guidelines is to avoid the use of abbreviation at all costs as this renders comments unclear. Instead of using an abbreviation you should use its expanded form. This applies to all abbreviations. This is also known as...

Instead of using: AKA ...

Javadoc Tags

The Javadoc tags are used to provide important or essential meta information about the code. Consider the @author tag in the class comment for the example given above, it gives important information as to who the author of the code is. Each tag has a specific format which we will now look at. Author Tag

Form: @author name

Used Where: Interface and Class comments.

Used For: Giving the names of the authors of the source code. You should use the full name of the author or "unascribed" when the author is unknown. Authors are listed in chronological order, with the creator of the class or interface being listed first. Since Tag

Form: @since version

Used Where: Interface and Class comments.

Used For: Indicates the version of the source code that this item was introduced. It is usually just a version umber but may also contain a specific date. Version Tag

Form: @version description

Used Where: Interface and Class comments.

Used For: Describes the current version number of the source code. This is often simply a version number including only the major and minor number and not build number. Some instances also include a date. Deprecated tag

Form: @deprecated

Used Where: Interface, class and method comments.

Used For: Used to indicated that an item is a member of the deprecated API. Deprecated items should not be used and are merely included for backwards compatibility. Parameter Tag

Form: @param name description

Used Where: Method comments.

Used For: Describes a method parameter. The name should be the formal parameter name. the description should be a brief one line description of the parameter. Return Tag

Form: @return description

Used Where: Method comments.

Used For: Describe the return value from a method with the exception of void methods and con tructors. Exception Tag

Form: @throws exception description

Used Where: Method comments.

Used For: Indicates any exceptions that the method might throw and the possible reasons for this exception occurring. See Class Tag

Form: @see classname

Used Where: Any item being commented.

Used For: If another class may help provide clarity this tag may be used to provide a link to that class. See Class Member Tag

Form: @see classname#member

Used Where: Any item being commented.

Used For: If another class's members may provide additional clarity this tag can be used to link to that class's member. General Order of Tags

The general order in which the tags occur is as follows: @author @version @param @return @throws @see @since @deprecated Ordering Multiple Tags

There are three tags that may occur more than once, thay are: @author @param @throws

As mentioned above, the author tag should be listed in chronological order, with the creator of the class or interface listed first. This implies that the last person to work on the source code will have their name appended to the bottom of the list of author tags.

A method may have numerous parameters. In this case, the param tags should be defined in the exact same order as the parameters are declared in the method declaration.

A method may throw numerous exceptions, in such a case it is customary to list the exceptions in alphabetical order, although in some cases they may be listed according to severity, the most severe exception is listed first. Tag Summary

What is a Package?

One of the many concerns that programmers face today is trying to ensure that their source code does not conflict with the source code of other programmers. A typical example is the case when two programmers define two distinct classes that have the same name. Suppose you decide to write a List class that keeps a sorted list of objects. This would inherently conflict with the List class in the Java API that is used to display a list of items in a Graphical User Interface. Java has a simple solution to this problem that is known as namespace management. Each programmer defines their own namespace and place their code within that namespace, thus two classes that have the exact same name are now distinguishable since they occur in different name spaces. Namespaces are called packages in Java.

Another important reason for using packages is that it provides programmers with greater control over their source code. It is typical to have a few thousand source files in medium to large scale applications, and trying to maintain them would be difficult at best, if not impossible. However, separating these source files into packages makes it much easier to manage the source code. What usually occurs is that related classes are grouped into a single package, for example, all the user interface classes of an application will be grouped into a package.

Access protection is another benefit of using packages. Suppose a group of different applications utilize the same set of source code, it would make sense to separate this source code and maintain it as a separate library that each application uses. In such a library, there is a public interface and a private interface. The public interface is those classes and methods that are accessible to the application using the library, while the private interface is not accessible to the application. Using a package makes it easier to define which classes form part of the public interface and which are part of the private interface. This makes it easy to control access to certain code sections.

Some of the benefits of using packages are: It shows that the classes and interfaces in the package are related. Often a group of classes and interfaces are related according to functionality so naturally they should be grouped into a package. An excellent example is the java.io package which groups a set of classes that all perform input and output functions. You know where to find the classes you want if they're in a specific package.

If you are looking for a specific class and you know what functionality it provides you will naturally be able to find it in the right package. If you are looking for an InputStreamReader you will find it in the input and output package, ie: java.io The names of your classes and interfaces won't be in conflict with those of other programmers. If you decide to implement your own String class and you place it in a package it will be distinguishable from the java.lang.String class that comes with the Java API. You can restrict the access to your classes. When you only want your code or program to access certain code, for example in a library, then using packages makes access control to source code much easier. Creating Packages

Creating a Java Package is relatively simple but may seem a bit confusing for people who have not done it before. There are two fundamental requirements for a package to exist: The package must contain one or more classes or interfaces. This implies that a package cannot be empty. The classes or interfaces that are in the package must have their source files in the same directory structure as the name of the package. Naming Packages

Since packages are used to create namespaces that are used to prevent the problem of name conflicts, namespaces must be unique. This means that package names must be unique. Naming a package is therefore a very important aspect of creating a package.

Often organizations that are involved in software development will use their organi ation's domain name, since domain names by definition are unique. The domain name is inverted to make it easier to read. Good examples can be found from looking at the source code of the Apache Software Foundation, whose domain name is www.apache.org. All their code is placed into packages that have names beginning with org.apache.

Since the Apache Software Foundation has a number of sub-projects, each with its own web address, the project name is also used in the package name. The Ant project can be found at

http://ant.apache.org, and it should be no surprise that their code is in the packages with names beginning with org.apache.ant.

When naming your package you should take your inverted domain name, if you have one, and add the project name to it. This will ensure that you have a unique package name, since it is highly unlikely that your organization is working on two projects that have the exact same name. As an example: com.mycompany.myproject

Some companies have decided to drop the top level domain (com, org, net, ...) from their package names for the sake of brevity, this is still perfectly acceptable: mycompany.mypackage Declaring Package Members

The first thing to do when creating a package is to decide which classes and interfaces should belong to that package. Once you have decided that, you need to specify this by adding a package declaration to the source file of each class and interface that is a part of the package.

The declaration is simple, you use the package keyword followed by the package name. This declaration comes right at the top of the source file, before any import statements. /* * File comments... */

package com.mycompany.myproject;

import java.util.*;

class MyClass {

Source and Class File Organization

One of the requirements for a package is that the source file should be contained in a directory structure that resembles the name of the package. This is simply creating a set of directories with the names given in the package name.

Take the package name and split it up according to where the periods (.) occur, for example, com.mycompany.myproject can easily be split up into three components, namely: com, mycompany and myproject. These will be the three directories that you create. The first directory will be the com directory and within this directory you will create a sub directory namely the mycompany directory and within that directory a sub directory, namely the myproject directory.

Finally, all the source files that are part of the package will go into the myproject directory.

It is typical in many java project to have the source code go into a src directory and when it is compiled, the resulting byte code goes into a classes directory. The package directories will therefore go into the src directory. As an example, consider a class named MyClass in the package named com.mycompany.myproject and all source code in the src directory. The following picture depicts this situation clearly:

Compiling The Package

At first it may seem like a nightmare trying to compile the package, especially having the resulting class files occur in the classes directory, but it can be achieved using a single command. You don't even need all the package directories under the classes directory since they will be created in the compilation.

To try this out, create a test directory and all the sub directories required: mkdir test mkdir test\src

mkdir test\classes mkdir test\src\com mkdir test\src\com\mycompany mkdir test\src\com\mycompany\myproject

Now create the MyClass source file named MyClass.java in the test\src\com\mycompany\myproject directory. /* MyClass.java * Author: Trevor Miller */ package com.mycompany.myproject;

public class MyClass {

Change into the test directory and compile the package: cd test javac -d ./classes/ ./src/com/mycompany/myproject/*.java

If you take a look in the classes directory, you will find the exact same directory structure as in the src directory. You'll also find a MyClass.class file in the test\classes\com\mycompany\mypackage directory. This is good as it allows you to keep your source and class files separate and provides greater control over your files.

Using Packages

Once you have created your package you may want to use it in your program or you may wish to use another programmer's package or the packages in the Java API. There are three ways of using the resources in a package; inline package member declarations, importing only the package member that you want and importing the entire package. Inline Member Declarations

In this approach you simply declare the package member you wish to use with its fully qualified package name. As an example, suppose you wish to use the Vector class in the java.util package. You can easily declare a vector using java.util.Vector vector;

When you initialize the object by calling its constructor, you will again have to use the fully qualified package name. class Test { java.util.Vector vector;

Test() { vector = new java.util.Vector(); } } Importing a Single Package Member

Using the inline declaration works well if you only use it a few times in your source code, but it can become a pain to type the fully qualified package name if you use it often. Instead you want to do this once and only once, and from then on, simply use the member's name wherever you need it.

This is easily achieved using an import statement in which the import keyword is followed by the fully qualified name of the member you wish to use. Consider the example given previously, but revised to use this method:

import java.util.Vector; class Test { Vector vector;

Test() { vector = new Vector(); } } Importing an Entire Package

It may be that you use a number of members from a package and end up with a large number of import statements. As an example consider the following: import java.util.Vector; import java.util.LinkedList; import java.util.Hashtable import java.util.Stack import java.util.Set

class Test { ... }

This can become messy quite quickly, and you would like to get away from this. The answer is to simply import the entire package, again using the import statement but instead of declaring the member you use a wildcard symbol to indicate that everything should be imported. The wildcard symbol is an asterisk (*), using this method you can replace all the import statements of the previous example with simply one import statement.

import java.util.*;

class Test { ... }

As you can see, this is much cleaner but it does have its limitations. If the package is very large and you import everything in the package, this will impact the performance of your program. You should consider carefully whether greater clarity in your code and ease of writing the code outweighs the addition of some overhead to the performance of your application. Summary

Packages are a great way to organize your source code and split source code from byte code (class files). Understanding how packages work is vital to writing quality software.

Вам также может понравиться