A package is a group of classes, interfaces and other packages. We can organize our classes and interfaces using packages. In java there are two types of packages.
- Built-in packages
- User defined packages
Built – In Packages
In java we can see packages that defined already. They are known as Built-in packages. Let’s see an example.
This package is used when we need user input.
java – top level package
util – sub package
Scanner – class that presents in the util package
User Defined Packages
That packages we create are called user defined packages. Let’s see an example.
Example.java file is created inside the package “abc”.
Let’s see how to use this package in another program.
To use the class “Example” inside the class “Test”, I have imported the package “abc”. In the above program i have imported the package as “abc.Example”. This only imports the “Example” class. Imagine that there are many classes inside the package “abc”. Then you can import the package like given below to use all of those classes inside the package.
You can create a class inside a package while importing another package also. The order should be like given below.
You can use fully qualified name to avoid the import statement. Lets see an example to understand this.
Here I have used the full qualified name such as package_name.class_name to create the object of it.
Sometimes class name conflict may occur. Assume that you created two classes with the same name in two different packages and you need to import all from those packages. Then that will throw a compile error. Therefore in that sort of situations you should use full qualified name method.
I hope you guys understood about the Java packages. This is important to learn the next article. It is on the topic “Java Access Modifiers”.
Thank you.