Packages
Fundamentals
ü One of the main features of object-oriented programming is its ability to reuse the code already created.
ü One way of achieving this is by extending the classes and implementing the interfaces we had created. This is limited to reusing the classes with in a program.
ü What if we need use classes from other programs with out physically copying them into the program under developments. This can be accomplished in Java with the help of packages.
ü Definition: Related classes and interfaces that are grouped by directories on disk are called packages.
Ex: import java.io.*; //Built-in package
Here, we are importing classes of java.io package. Here, java is a directory name and
io is another sub directory within it. And the * represents all the classes and interfaces
of that io sub directory.
Advantages of packages
ü Packages are useful to arrange related classes and interfaces into a group. This makes all the classes and interfaces performing the same task to put together in the same package. For example, in Java all the classes and interfaces which perform input and output operations are stored in java.io package.
ü Packages hide the classes and interfaces in a separate sub directory, so that accidental deletion of classes and interfaces will not take place.
ü The classes and interfaces of a package are isolated from the classes and interfaces of another package. This means that we can use same names for classes of two different classes. For example, there is Date class in java.util package and also there is another Date class available in java.sql package.
ü A group of packages is called a library. The classes and interfaces of a package are like books in a library and can be reused several times. This reusability nature of packages makes programming easy. Just think, the packages in Java are created by JavaSoft people only once, and millions of programmers all over the world are daily by using them in various programs.
Types of packages:
There are two different types of packages in Java. They are
- Built-in packages.
- User-defined packages.
Built-in packages:
ü These are the packages which are already available in Java language. These packages provide all most all necessary classes, interfaces and methods for the programmer to perform any task in the programs.
ü Java has an extensive library of packages, a programmer need not think about logic for doing any task. For everything, there is a method available in Java and that method can be used by the programmer without developing the logic on his/her own. This makes the programming easy.
ü Ex: java.lang: lang stands for language
java.util: util stands for utility
java.io: io stands for input and output
java.awt; awt stands for abstract window tool kit
java.net: net stands for network.
User-defined packages:
ü Just like Built-in packages, the users of Java language can also create their own packages. They are called user-defined packages. User-defined packages can also be imported into other classes and used exactly in the same way as Built-in packages.
ü To create a package, simply include a package command as the first statement in a Java source file. Any classes declared within that file will belong to the specified package.
ü The package statement defines a name space in which classes are stored. If you omit the package statement, the class names are put into the default package, which has no name.
ü Limitations:
· package must be a first statement of the program.
· Must ends with the semicolon (;).
· First letter of the package should be small.
· All methods and class itself in a package should be declared as public except that the instance variables. The reason is only that the public members are available outside the package to other programs.
ü Syntax: package packagename; // to cteate a package
package packagename.subpackagename; //to create a sub package within a // package
Program1: To create a package with the name pack and store Addition class in it
package pack; //pack is the package name
public class Addition
{
private double d1,d2; //instance variables
public Addition(double a, double b)
{
d1=a;
d2=b;
}
public void sum()
{
System.out.println(“Sum=”+(d1+d2));
}
}
Compile: C:\Madhava>md pack
C:\Madhava\pack> javac Addition.java
ü This command means create a package (pack) in the current directory (Madhava) and store Addition.class file in the package.
ü So, our package with Addition class is ready. The next step is to use the Addition class and its sum() method in a program. For this purpose, we write another class Use.
ü In the following program, we can refer to the Addition class of package pack using membership operator(.) as pack.Addition and to create an object to Addition class, we can write as:
pack.Addition ob= new pack.Addition(10,15.5);
Program2: Which depicts how to use the Addition class of package pack
class Use
{
public static void main(String args[])
{
//create Addition class object
pack.Addition ob=new pack.Addition(10,15.5);
//call the sum() method
ob.sum();
}
}
Output: C:\Madhava\pack>java pack.Addition //Error
C:\Madhava> java pack.Addition
Sum=25.5
Program3: Which is using import statement to import a package and its classes into a program?
import pack.Addition;
class Use
{
public static void main(String args[])
{
//create Addition class object
Addition ob=new Addition(10,15.5);
ob.sum();
}
}
Output: C:\Madhava>javac Use.java
C:\Madhava>java Use
Sum=25.5
Program4: To add another class Subtraction to the same package pack.
package pack;
public class Subtraction
{
// a static method to return result of subtraction
public static double sub(double a, double b)
{
return (a-b);
}
}
Compile: C:\Madhava\pack> javac Subtraction.java
Note: Here, i am saving Addition.java and Subtraction.java manually.
Program5: Let us make a program using both the Addition and Subtraction classes of the package pack.
import pack.Addition;
import pack.Subtraction;
class Use
{
public static void main(String args[])
{
//create Addition class object
Addition ob=new Addition(10,15.5);
ob.sum();
//call the sub() method and pass values
double res=Subtraction.sun(10,15.5);
System.out.println(“Result=”+res);
}}
Output: C:\Madhava>javac Use.java
C:\Madhava>java Use
Sum=25.5
Result = -5.5
CLASSPATH:
ü Of course, the package pack is available in the current directory. If the packages is not available in the current directory, then what happens? Suppose our program is running in C:\Madhava and the package pack is available in the directory D:\Ramesh. In this case, the compiler should be given information regarding the package location by mentioning the directory name of the package in class path.
ü Class path represents an operating system’s environment variable which stores active directory path such that all the files in those directories are available to any programs in the system. Generally, it is written in all capital letters as CLASSPATH.
ü If our package exists in D:\Ramesh, then set the class path like this:
C:\Madhava>set CLASSPATH=D:\Ramesh;.;%CLASSPATH%
then we can execute our program Use.java in C:\Madhava
C:\Madhava> javac Use.java
The JAR Files:
ü A JAR (Java Archive)file is a file that contains compressed version of .class files, audio files, image files or directories. We can imagine a .jar file as a zipped file (.zip) that is created by using WinZip software. Even, WinZip software can be used to extract the contents of a .jar file. The difference is that a .jar file an be used as it is but whereas the .zip file an not be used directly. The files should be extracted first from a .zip file, and then used.
ü Let us see how to create a .jar file and related commands which help us to work with .jar files:
· To create .jar file, JavaSoft people have provided jar command, which can be used in the following way:
jar cf jarfilename inputfiles
Here, cf represents create file. For example, assuming our package pak is available in
C:\Madhava> directory, to convert it into a jar file with the name pack.jar, we can
give the command as:
C:\Madhava>jar cf pack.jar pack
Now, pack.jar file is created.
· To view the contents of a .jar files, we can use the jar command as:
jar tf filename
Here, tf represents table view of file contents. For example, to view the contents of
our pack.jar file, we can use the command as:
C:\Madhava>jar tf pack.jar
now the contents of pack.jar are displayed as:
META-INF/
META-INF/MANIFEST.MF
pack/
pack/Addition.class
pack/Addition.java
pack/Subtraction.class
pack/Subtraction.java
The first two entries represent that there is a manifest file created and added to
pack.jar file. The third entry represents the sub directory with the name pack and the
last four statements represent the file names in the directory pack.
When we create a .jar file, it automatically receives the default manifest file. there can
be only one manifest file in an archive, and it always has the pathname.
META-INF/MANIFEST.MF
This manifest file is useful to specify the information about other files which are
packed.
· To extract the jar files from a .jar file, we can use:
jar xf filename
Here, xf represents extract files from the jar file. For example, to extract the contents
of our pack.jar file, we can write;
C:\Madhava>jar xf pack.jar
This will create the following directories in C:\Madhava
MATA-INF
Creating a Sub package in a package:
ü We can create sub package in a package in the following format:
package pack1.pack2;
Here, we are creating pack2 which is created inside the pack1. To use the classes and
interfaces of pck2, we can write import statement as:
import pak1.pack2;
Program: Let us make a program to learn how to create a sub package in a package.
package prasad.murali;
public class Ramesh
{
public void show()
{
System.out.println(“Welcome to Sub package”);
}
}
Compile: C:\Madhava>cd prasad
C:\Madhava\prasad>cd murali
C:\Madhava\prasad\murali>javac Ramesh.java
C:\Madhava\prasad\murali>
Program: Let us make a program using Madhava class of prasad.murali package
import prasad.murali.Ramesh;
class Use
{
public static void main(String args[])
{
Sample s=new Sample();
s.show();
}
}
Output: C:\Madhava>javac Use.java
C:\Madhava>java Use
Welcome to Sub package
Access Specifiers:
ü We have seen that any class and its members within a package should be declared as public. Then only the class and its members will be available for use outside of the package.
ü An access specifier is keyword that is used to specify how to access a member of a class or the class itself.
ü There are four access specifiers in Java: private, public, protected, and default. We do not use default keyword for specifying the default access specifier. If no other access specifier is used, then Java compiler will take it as default access specifier.
ü In the following figure, we are taking three classes, class A, class B and class C. Whereas class A and class B exists in the same package (directory), class C is away from them in another package (another directory). Let us assume that there are four members with private, public, protected and default specifiers in class A. Now let us discuss which of these members will be available to class B and class C.
Figure: Availability of access specifier in packages.
· private members of class A are not available to class B or class C. This means, any private member’s scope is limited only to that class where it is defined. So the scope of private access specifier is class scope.
· public members of class A are available to class B and also class C. This means, public members are available every where and their scope is global scope.
· protected members of class A are available to class B, but not in class C. But if, class C is a sub class of class A, then the protected members of class A are available to class C. So, protected access specifier acts as public with respect to sub classes.
· When no access specifier is used, it is taken as default specifier. Default members of class A are accessible to class B which is within the same package. They are not available to class C. This means, the scope of default members is package scope.
Program1: To create class A with different access specifiers
package same;
public class A
{
private int a=1;
public int b=2;
protected int c=3;
int d=4; //default
}
Compile: C:\Madhava\same> javac A.java
Program2: For creating class B in the same package
package same;
import same.A;
public class B
{
public static void main(String args[])
{
//access the members of class A
A ob=new A();
System.out.println(“A:”+ob.a+”B:”+ob.b+”C:”+ob.c+”D:”+ob.d);
}
}
Output:C:\Madhava\same>javac B.java
B.java:9: a has private access in same.A
System.out.println(“A:”+ob.a+”B:”+ob.b+”C:”+ob.c+”D:”+ob.d);
Technical Interview Questions and Answers:
1. What is a CLASSPATH?
Ans: The CLASSPATH is an environment variable that tells the Java compiler where to look for class files to import. CLASSPATH is generally set to a directory or a JAR file.
2. What is a JAR file?
Ans: A Java Archive file is a file that contains compressed version of several .class files, audio files, image files or directories. JAR file is useful to bundle up several files related to a project and use them easily.
The package java.util.zip contains classes that read and write jar files.
3. What is the scope of default access specifier?
Ans: Default members are available within the same package, but not outside of the package. So their scope is package scope.
4. What are packages, and what are they used for?
Ans: A package is a collection of classes and interfaces that provides a high-level layer of access protection and name space management.
5. Is there a default access modifier for classes and interfaces? For class members(methods, constructors and fields)?
Ans: There is no default access modifier; the absence of a modifier, though, signals package-level access, which is access only from classes in the same package.
6. What does protected access mean?
Ans: A method, constructor, or field with protected access is accessible to all classes in the same package, and to sub classes in other package provided that the class granting the access is the same as or a sub class of the class making the access.
7. What is difference between importing "java.applet.Applet" and "java.applet.*;"?
Ans :"java.applet.Applet" will import only the class Applet from the package java.applet
Where as "java.applet.*" will import all the classes from java.applet package.
8. What do you understand by package access specifier?
Ans : public: Anything declared as public can be accessed from anywhere
private: Anything declared in the private can’t be seen outside of its class.
protected: It is visible to subclasses as well as to other classes in the same package
9. By default, all program import the java.lang package.
Ans : Yes, all program import the java.lang package.
10. Java compiler stores the .class files in the path specified in CLASSPATH environmental variable.
True/False
Ans : False
11. User-defined package can also be imported just like the standard packages.
True/False
Ans : True
12. All standard classes of Java are included within a package called _____.
Ans : java.lang
13. All the classes in a package can be simultaneously imported using ____.
Ans : *
14. State the significance of public, private, protected, default modifiers both singly and in combination and state the effect of package relationships on declared items qualified by these modifiers.
Ans: public : Public class is visible in other packages, field is visible everywhere (class must be public too)
private : Private variables or methods may be used only by an instance of the same class that declares the variable or method, A private feature may only be accessed by the class that owns the feature.
protected : Is available to all classes in the same package and also available to all subclasses of the class that owns the protected feature. This access is provided even to subclasses that reside in a different package from the class that owns the protected feature.
default :What you get by default i.e., without any access modifier (i.e., public private or protected).It means that it is visible to all within a particular package.
default :What you get by default i.e., without any access modifier (i.e., public private or protected).It means that it is visible to all within a particular package.
15. Do I need to import java.lang package any time?
Ans: No. It is by default loaded internally by the JVM.
16. Can I import same package/class twice? Will the JVM load the package twice at runtime?
Ans: One can import the same package or same class multiple times. Neither compiler nor JVM complains about it. And the JVM will internally load the class only once no matter how many times you import the same class.
17. Can a top level class be private or protected?
Ans: No. A top level class can not be private or protected. It can have either "public" or no modifier. If it does not have a modifier it is supposed to have a default access. If a top level class is declared as private the compiler will complain that the "modifier private is not allowed here". This means that a top level class can not be private. Same is the case with protected.
18. What restrictions are placed on the location of a package statement within a source code file?
Ans: A package statement must appear as the first line in a source code file (excluding blank lines and comments).
19. If a variable is declared as private, where may the variable be accessed?
Ans: A private variable may only be accessed within the class in which it is declared.
20. Which package is always imported by default?
Ans: The java.lang package is always imported by default.
