Packages In JAVA | Core Java Tutorial | Minigranth
Packages In Java : Introduction
Packages in java are like container which keeps classes, interfaces and sub-packages in an organized way. You can visualize packages as folders in your computer. Folder houses sub-folders and other files.
Similarly Java package contains collection of related classes, interfaces and sub-packages.
Packages In Java : Advantages
Prevent naming conflicts. Every time a new package is created a new namespace for that package is created and hence class names for different packages can be same. In Java you will find classes with same name but they will be part of different packages.
Packages in java keep classes, sub-packages, interfaces etc. in organized manner.
Provides access protection.
Packages like classes are the means to provide encapsulation. We can create Java classes which are limited to that package only and hence cannot be accesses outside the package.
Examples of some packages in java include java.lang, java.io, java.util, java.awt etc. We can also create our own package in Java.
Defining, Compiling and Running Packages In Java
To Define Package
We can also create package hierarchy by writing different package names separated by a (.)
Above statement should be the first line in the code.
To Compile Java Programs Containing Packages(In Command Prompt)
To Run Java Program Containing Packages(In Command Prompt)
Program Execution : Example
Program Execution : Output
Importing Packages In Java
Importing a packages in Java means making all the classes and interfaces declared in the package available to the current class.
Packages in Java can be imported to current code by using import.
If we want to use classes within packages to other source code we have to mention the fully qualified name having package name.
This will become tiring if we use many class of that package.
Hence we use import keyword to make all the classes and interfaces available to current program and then we can use the classes without using fully qualified name.
Import statement occurs after the package statement in source code.
Syntax For Importing Package
In import statement we can have hierarchy of packages.
To import the whole package we use a wildcard character (*)