Packages in Java, Syntax, Types and Examples

Packages in Java:

Packages in Java: Packages are defined in Java to know about the classes or interfaces location in projects. No project is defined in world without packages.

In other words, package is set of programs by types which help to organize properly.

Each packages may have its own classed defined.

"Package" is a keyword which is a combination of words separated by delimiter ".".

In Java, Package is the first statement in every class.


Packages in Java



Package Example:


package org

Package Members:

The members of packages are its sub-packages. Super package can have access to all its sub-packages classes and interfaces.


Below are the user defined packages. "org.java.w3schools.core" is super package and action, model, service, constants are subpackages.

package org.java.w3schools.core.action
package org.java.w3schools.core.model
package org.java.w3schools.core.service
package org.java.w3schools.core.constants
package org.java.w3schools.conversions

We will see some packages in Java API(Application Programming Interface).

In Java basic api, Super packages are "java", "javax" and "org".

java is super package which has subpackages lang, io, sql, beans, awt etc.
javax is super package which has subpackages rmi, net, sql, swings etc.
org is another super package which has suvpackages omg, w3c, xml etc

We have two sql pakcages.

a) java.sql : Provides the API for accessing and processing data stored in a data source (usually a relational database) using the JavaTM programming language.
b) javax.sql : Provides the API for server side data source access and processing from the JavaTM programming language. 

Package Declarations :

A package declaration appears within a compilation unit to indicate the package to which the compilation unit belongs.


1) Named Packages :


A class which has package specified.


Syntax :

{Package Modifier} package Identifier {. Identifier} ;

Eg. org.java.w3schools.action



package org.java.w3schools.core.constants; // Package Name

/**
* @author Java-W3schools Blog
* @File Name EmployeeConst.java
*/
public class EmployeeConst {

public static final String SCHOOL_NAME = "OXFORD";
}



2) Unnamed Packages:



A class which has no package is called "Unnamed Package" and are in default package.


Example:



/**

* @author Java-W3schools Blog

* @File Name NoName.java

*/

public class NoName {

}

0 Comments