Java Tutorial
Packages in java and how to use them
A package as the name suggests is a pack(group) of classes, interfaces and other packages. In java we use packages to organize our classes and interfaces. We have two types of packages in Java: built-in packages and the packages we can create (also known as user defined package). In this guide we will learn what are packages, what are user-defined packages in java and how to use them.
In java we have several built-in packages, for example when we need user input, we import a package like this:
Here: →java is a top level package →util is a sub package →and Scanner is a class which is present in the sub package util.
Advantage of Java Package
These are the reasons why you should use packages in Java:
- Reusability: While developing a project in java, we often feel that there are few things that we are writing again and again in our code. Using packages, you can create such things in form of classes inside a package and whenever you need to perform that same task, just import that package and use the class.
- Better Organization: Again, in large java projects where we have several hundreds of classes, it is always required to group the similar types of classes in a meaningful package name so that you can organize your project better and when you need something you can quickly locate it and use it, which improves the efficiency.
- Name Conflicts: We can define two classes with the same name in different packages so to avoid name collision, we can use packages
Simple example of java package
The package keyword is used to create a package in java.
//save as Simple.java package mypack; public class Simple < public static void main(String args[])< System.out.println("Welcome to package"); >>
How to compile java package
If you are not using any IDE, you need to follow the syntax given below:
javac -d directory javafilename
For example
The -d switch specifies the destination where to put the generated class file. You can use any directory name like /home (in case of Linux), d:/abc (in case of windows) etc. If you want to keep the package within the same directory, you can use . (dot).
Types of packages in Java
As mentioned in the beginning of this guide that we have two types of packages in java.
- User defined package: The package we create is called user-defined package.
- Built-in package: The already defined package like java.io.*, java.lang.* etc are known as built-in packages.
We have already discussed built-in packages, lets discuss user-defined packages with the help of examples.
How to run java package program
You need to use fully qualified name e.g. mypack.Simple etc to run the class.
To Compile: javac -d . Simple.java To Run: java mypack.Simple Output:Welcome to package
The -d is a switch that tells the compiler where to put the class file i.e. it represents destination. The . represents the current folder.
Example 1: Java packages
I have created a class Calculator inside a package name letmecalculate. To create a class inside a package, declare the package name in the first statement in your program. A class can have only one package declaration.
Calculator.java file created inside a package letmecalculate
package letmecalculate; public class Calculator < public int add(int a, int b)< return a+b; >public static void main(String args[]) < Calculator obj = new Calculator(); System.out.println(obj.add(10, 20)); >>
Now lets see how to use this package in another program.
import letmecalculate.Calculator; public class Demo < public static void main(String args[])< Calculator obj = new Calculator(); System.out.println(obj.add(100, 200)); >>
To use the class Calculator, I have imported the package letmecalculate. In the above program I have imported the package as letmecalculate.Calculator, this only imports the Calculator class. However if you have several classes inside package letmecalculate then you can import the package like this, to use all the classes of this package.
How to access package from another package?
There are three ways to access the package from outside the package.
1) Using packagename.*
If you use package.* then all the classes and interfaces of this package will be accessible but not subpackages.
The import keyword is used to make the classes and interface of another package accessible to the current package.
Example of package that import the packagename.*
//save by A.java package pack; public class A < public void msg()>
//save by B.java package mypack; import pack.*; class B < public static void main(String args[])< A obj = new A(); obj.msg(); >>
Output:
2) Using packagename.classname
If you import package.classname then only declared class of this package will be accessible.
Example of package by import package.classname
//save by A.java package pack; public class A < public void msg()>
//save by B.java package mypack; import pack.A; class B < public static void main(String args[])< A obj = new A(); obj.msg(); >>
Output:
3) Using fully qualified name
If you use fully qualified name then only declared class of this package will be accessible. Now there is no need to import. But you need to use fully qualified name every time when you are accessing the class or interface.
It is generally used when two packages have same class name e.g. java.util and java.sql packages contain Date class.
Example of package by import fully qualified name
//save by A.java package pack; public class A < public void msg()>
//save by B.java package mypack; class B < public static void main(String args[])< pack.A obj = new pack.A();//using fully qualified name obj.msg(); >>
Output:
Note: If you import a package, subpackages will not be imported.
If you import a package, all the classes and interface of that package will be imported excluding the classes and interfaces of the subpackages. Hence, you need to import the subpackage as well.
Note: Sequence of the program must be package then import then class.
Creating a class inside package while importing another package
As we have seen that both package declaration and package import should be the first statement in your java program. Lets see what should be the order when we are creating a class inside a package while importing another package.
//Declaring a package package anotherpackage; //importing a package import letmecalculate.Calculator; public class Example < public static void main(String args[])< Calculator obj = new Calculator(); System.out.println(obj.add(100, 200)); >>
So the order in this case should be:
Using fully qualified name while importing a class
You can use fully qualified name to avoid the import statement. Lets see an example to understand this:
Calculator.java
package letmecalculate; public class Calculator < public int add(int a, int b)< return a+b; >public static void main(String args[]) < Calculator obj = new Calculator(); System.out.println(obj.add(10, 20)); >>
Example.java
//Declaring a package package anotherpackage; public class Example < public static void main(String args[])< //Using fully qualified name instead of import letmecalculate.Calculator obj = new letmecalculate.Calculator(); System.out.println(obj.add(100, 200)); >>
In the Example class, instead of importing the package, I have used the full qualified name such as package_name.class_name to create the object of it. You may also want to read: static import in Java
Subpackage in java
Package inside the package is called the subpackage. It should be created to categorize the package further.
A package inside another package is known as sub package. For example If I create a package inside letmecalculate package then that will be called sub package.
Lets say I have created another package inside letmecalculate and the sub package name is multiply. So if I create a class in this subpackage it should have this package declaration in the beginning:
Let’s take an example, Sun Microsystem has definded a package named java that contains many classes like System, String, Reader, Writer, Socket etc. These classes represent a particular group e.g. Reader and Writer classes are for Input/Output operation, Socket and ServerSocket classes are for networking etc and so on. So, Sun has subcategorized the java package into subpackages such as lang, net, io etc. and put the Input/Output related classes in io package, Server and ServerSocket classes in net packages and so on.
The standard of defining package is domain.company.package e.g. com.javatpoint.bean or org.sssit.dao.
Example of Subpackage
package com.javatpoint.core; class Simple < public static void main(String args[])< System.out.println("Hello subpackage"); >>
Sun package in java
The java.*, javax.* and org.* packages documented in the Java Platform Standard Edition API Specification make up the official, supported, public interface.
If a Java program directly calls only API in these packages, it will operate on all Java-compatible platforms, regardless of the underlying OS platform.
The sun.* packages are not part of the supported, public interface.
A Java program that directly calls into sun.* packages is not guaranteed to work on all Java-compatible platforms. In fact, such a program is not guaranteed to work even in future versions on the same platform.
Each company that implements the Java platform will do so in their own private way. The classes in sun.* are present in the JDK to support Oracle’s implementation of the Java platform: the sun.* classes are what make the Java platform classes work «under the covers» for Oracle’s JDK. These classes will not in general be present on another vendor’s Java platform. If your Java program asks for a class «sun.package.Foo» by name, it may fail with ClassNotFoundError, and you will have lost a major advantage of developing in Java.
Technically, nothing prevents your program from calling into sun.* by name. From one release to another, these classes may be removed, or they may be moved from one package to another, and it’s fairly likely that their interface (method names and signatures) will change. (From Oracle’s point of view, since we are committed to maintaining the Java platform, we need to be able to change sun.* to refine and enhance the platform.) In this case, even if you are willing to run only on Oracle’s implementation, you run the risk of a new version of the implementation breaking your program.
In general, writing java programs that rely on sun.* is risky: those classes are not portable, and are not supported.
Sun package in java
Starting in 1996, Alexa Internet has been donating their crawl data to the Internet Archive. Flowing in every day, these data are added to the Wayback Machine after an embargo period.
The Wayback Machine — http://web.archive.org/web/19980215011039/http://java.sun.com:80/products/jdk/faq/faq-sun-packages.html
Why Developers Should Not Write Programs
That Call ‘sun’ Packages
The classes that JavaSoft includes with the JDK fall into at least two packages: java.* and sun.*. Only classes in java.* packages are a standard part of the Java Platform and will be supported into the future. In general, API outside of java.* can change at any time without notice, and so cannot be counted on either across OS platforms (Sun, Microsoft, Netscape, Apple, etc.) or across Java versions. Programs that contain direct calls to the sun.* API are not 100% Pure Java. In other words:
The java.* packages make up the official, supported, public Java interface.
If a Java program directly calls only API in java.* packages, it will operate on all Java-compatible platforms, regardless of the underlying OS platform.
The sun.* packages are not part of the supported, public Java interface.
A Java program that directly calls any API in sun.* packages is not guaranteed to work on all Java-compatible platforms. In fact, such a program is not guaranteed to work even in future versions on the same platform.
For these reasons, there is no documentation available for the sun.* classes. Platform-independence is one of the great advantages of developing in Java. Furthermore, JavaSoft, and our licensees of Java technology, are committed to maintaining the APIs in java.* for future versions of the Java platform. (Except for code that relies on bugs that we later fix, or APIs that we deprecate and eventually remove.) This means that once your program is written, the binary will work in future releases. That is, future implementations of the java platform will be backward compatible.
Each company that implements the Java platform will do so in their own private way. The classes in sun.* are present in the JDK to support the JavaSoft implementation of the Java platform: the sun.* classes are what make the classes in java.* work «under the covers» for the JavaSoft JDK. These classes will not in general be present on another vendor’s Java platform. If your Java program asks for a class «sun.package.Foo» by name, it will likely fail with ClassNotFoundError, and you will have lost a major advantage of developing in Java.
Technically, nothing prevents your program from calling API in sun.* by name, but these classes are unsupported APIs, and we are not committed to maintaining backward compatibility for them. From one release to another, these classes may be removed,or they may be moved from one package to another, and it’s fairly likely that the API (method names and signatures) will change. (From the JavaSoft point of view, since we are committed to maintaining the java.* APIs, we need to be able to change sun.* to enhance our products.) In this case, even if you are willing to run only on the JavaSoft implementation, you run the risk of a new version of the implementation breaking your program.
In general, writing java programs that rely on sun.* is risky: they are not portable, and the APIs are not supported.
Copyright © 1996 Sun Microsystems, Inc., 2550 Garcia Ave., Mtn. View, CA 94043-1100 USA. All rights reserved.