Package in Java
Package in java
A package is nothing but a physical folder structure (directories) that contains a group of related classes, interfaces, and sub-packages according to their functionality.
- Using package keyword user can create user-defined package.
For example:
package myPackage;
public class A {
// class body
}
Advantage of using packages in Java
1. Maintenance: Java packages are used for proper maintenance.
2. Reusability: We can place the common code in a common folder so that everybody can check that folder and use it whenever needed.
3. Name conflict: Packages help to resolve the naming conflict between the two classes with the same name.
4. Organized: It also helps in organizing the files within our project.
5. Access Protection: A package provides access protection
Types of packages
Packages can be categorized in two types :
1. User defined packages
2. Built-in packages
1. User-defined Package
The package which is defined by the user is called a User-defined package. It contains user-defined classes and interfaces.
Creating of Package .
Example:
package mypack;
class Test {
...
}
2. Predefined Packages (Built-in Packages)
Predefined packages in java are those which are developed by Sun Microsystem or Java. They are also called built-in packages in java.
Ex : Java.lang: he Java language package consists of java classes and interfaces that form the core of the Java language and the JVM. It is a fundamental package that is useful for writing and executing all Java programs.
compilation package in Java
Syntax:
To Compile the application: javac -d directory javafilename
1. Here, javac means java compiler.
2. -d means directory. It creates the folder structure.
3. .(dot) means the current directory. It places the folder structure in the current working directory.
For example: javac -d. className.java // Here, className.java is the file name.
How to Run package in Java
Syntax:
java completePackageName.className
Importing packages in Java
There are three approaches to import one package into another package in Java.
1. import package.*;
2. import package.classname;
3. Using fully qualified name.
Comments
Post a Comment