Packages in java

  • Packages in java are used to organize relevent classes and interfaces
  • Every class in java belongs to a package
  • If package is not explicitly defined, class will use a default package
  • Classes with similar functions can be placed in the same package to make them easy to locate
  • Packages are also used to avoid from class naming conflicts
  • Packages are also used to group related classes so that they can be easily distributed
  • A class or interface can indicate that its Java byte code be placed in a particular package, using a package declaration
  • Package declaration appears in a source file, and it must be the first statement
  • Provide protection so that the protected members of the classes are accessible to the classes in the same, but not to the external classes
  • One can create a package inside another package
  • Using class from the other packages, write import statement
    import java.lang.Math; //to access math class only


    import java.lang.*; //use * to import on demand

For example :


indicates that Math is a class in lang package and that lang is a package in java package. To use Math class one must write the import statement. The following package hirarchy a is wrong because com can’t be a root folder. where as is a correct hirarchy.

Package Hirarchy

Package Hirarchy

Example 1 : Student Class in student package

package student; //Package name is student. 
                 //Student class is defined inside the student package. 
class Student{
  private int ID;
  private String name;

No Responses