What are Java packages? Explain the importance of Java packages.A package is a group of .class files.
1. The .class files are organized into namespaces
2. The java packages are compressed into files known as Java Archive files
3. The classes are allowed to download faster as a group rather than a single class at a time.
4. Developers typically uses packages for organizing classes that are belonging to certain modules to provide similar functionalityImportance of packages
1. Packages provide unique naming space for all the types it contains
2. All classes in the same package can be accessed by each other package access members
3. Programmers are provided the facility to find the types that can provide module related functionalities
4. Same class names can be used in different packages, as the packages a new name space for each individual class
5. Using packages, restrictions to the class members can be imposed and still certain classes can have unrestricted access to its members
Steps for creating a package in JavaSteps for creating a package in Java.
1. Select the name of the package
2. Specify the ‘package’ statement followed by the name of the package at the top of the source file.Example
3. The source file will be placed in the package specified
4. The ‘package’ statement must be the first process instruction in the java source file and no code is allowed above the ‘package’ statement.Using packages
1. The packages are loaded in the applications by using ‘import’ statementExample
2. The statement communicates to “load all the .class files stored in the package”.
3. The above import statement loads all .class files found in the directory june2010.
4. This location should be communicated to CLASSPATH environment variable, so that the applications can use the .class files
5. Packages provides a facility to organize the .class files be developers for better modularity and easy to maintainExample
// Creates a package under com package
public class Cookie
public void show()
System.out.println("show method invoked");
In the initial class write the following code to access the Cookie class
public class Dinner
public static void main(String args)
Cookie cookie = new Cookie();
Explain the packages access specifier, i.e. private, protected, public, default
Access specifiers allows attributes and methods of a class to be accessed within a scope
They are used to hide or show the internal details of classes
They are –private
: All the private members can be accessed only within the class they are definedpublic
: All the public members can be accessed across the packages without restrictionsprotected
: All the protected members can be accessed within the class they are defined and sub classes of all other packages. If the class attributes or methods does not have any access specifier, they can be used by the classes within that package.