Packages in Java
Packages in Java
Packages in Java
Preventing naming conflicts. For example there can be two classes with
name Employee in two packages, college.staff.cse.Employee and
college.staff.ee.Employee
Making searching/locating and usage of classes, interfaces, enumerations
and annotations easier
Providing controlled access: protected and default have package level
access control. A protected member is accessible by classes in the same
package and its subclasses. A default member (without any access
specifier) is accessible by classes in the same package only.
Packages can be considered as data encapsulation (or data-hiding).
All we need to do is put related classes into packages. After that, we can simply write an
import class from existing packages and use it in our program. A package is a container
of a group of related classes where some of the classes are accessible are exposed
and others are kept for internal purpose.We can reuse existing classes from the
packages as many time as we need it in our program
Choose a name for the package and include a package command as the first statement
in the Java source file. The java source file can contain the classes, interfaces,
enumerations, and annotation types that you want to include in the package. For
statement of your program. Then include the class as part of the package. But,
remember that, a class can have only one package declaration. Here’s a simple
package MyPackage;
1
Both the values are same
I have first declared the package svew, then imported the class Compare from the
package MyPackage. So, the order when we are creating a class inside a package
Package Declaration
Package Import
If you do not want to use the import statement, there is another alternative to access a
class file of the package from another package. You can just use a fully qualified name
while importing a class.
Here’s an example to understand the concept. I am going to use the same package that
Package svew;
public class Demo{
public static void main(String args[]) {
int n=10, m=11;
//Using fully qualified name instead of import
MyPackage.Compare current = new MyPackage.Compare(n,
m);
if(n != m) {
current.getmax();
}
else {
System.out.println("Both the values are same");
}
}
}
Output:
Maximum value of two numbers is
11
programmer to access any static member of a class directly without using the fully
qualified name.
package MyPackage;
import static java.lang.Math.*; //static import
import static java.lang.System.*;// static import
public class StaticImportDemo {
public static void main(String args[]) {
double val = 64.0;
double sqroot = sqrt(val); // Access sqrt() method
directly
out.println("Sq. root of " + val + " is " + sqroot);
//We don't need to use 'System.out
}
}
Output:
1
Sq. root of 64.0 is 8.0