16 Просмотры
Adding a Class to a Package
It is simple to add a class to an existing package. Consider the following package:
package pl;
public classA
The package pl contains one public class by name A.
Suppose we want to add another class B to this package. This can be done as follows:
1. Define the class and make it public.
2. Place the package statement
package p1;
before the class definition as :
package p1;
public classB
body of B
3. Store this as file under the directory pl.
4. Compile file. This will create a B.class file and place it in the directory pl.
Note that we can also add a non-public class to a package using the same procedure. Now, the package p1 will contain both the classes A and B. A statement like
import pl.*;
will import both of them,
Remember that, since a Java source file can have only one class declared as public, we cannot put two or more public classes together in A .java file. This is because of the restriction that the file name should be same as the name of the public class with .java extension
If we want to create a package with multiple public classes in it, we may follow the following steps:
1. Decide the name of the package.
2. Create a subdirectory with this name under the directory where main source files are stored.
3. Create classes that are to be placed in the package in separate source files and declare the package statement
package packagename;
at the top of each source file.
4. Switch to the subdirectory created earlier and compile each source file. When completed, the package would contain .class files of all the source files.
Hiding Classes
When we import a package using asterisk (*), all public classes are imported. However, we may prefer to “not import” certain classes. That is, we may like to hide these classes from accessing from outside
of the package. Such classes should be declared “not public”.Example:
Package p1;
public classX // public class, available outside
body of X
classY // not public class, hidden
body of Y
Here, the class Y which is not declared public is hidden from outside of the package pl. This class can be seen and used only by other classes in the same package. Note that a Java source file should contain only one public class and may include any number of non-public classes. We may also add a single non-public class using the procedure suggested in the previous section.
Now, consider the following code, which imports the package pl that contains classes X and Y:
import p1.*;
x objectX; // OK: class X is available here
y objectY; // Not OK: Y is not available
Java compiler would generate an error message for this code because the class Y, which has not been declared public, is not imported and therefore not available for creating its objects.
Язык программирования Java
Комментариев нет.