Package Tutorial

Package in Java

Package is a keyword that is used to manage group of classes and sub packages.

Using package you can remove confliction between file name.

Using package you can also hold group of public class.

Sub package can never import automatic we need to import it explicitly.

There are two type of packages:

  1. Predefine or Built package
  2. User Define package

1. Predefine or Built package

Java provide following built packages for performing different type of task:

Note : By default java.lang package is imported automatic so we never import it.

2. User Define package

you can also create your package to manage your group of classes or sub packages.

1. How to declare a package ?

Using package keyword and name of the package you can declare a package.

package  packagename;

2. How to declare a sub package ?
package  packagename.subpackagename;

3. Where to declare a package ?

Package declaration must be top in a file.

        package  packagename;
        public class A{

        }
    

4. Can we write anything above the package declaration ?

You can write only comments above the package declaration.

        //comments only
        package  packagename;
        public class A{

        }
    

5. How to save a file ?

You can save a file with class name.

classname.java

6. How to create a package ?

You can create a package using following commands:

javac -d . filename.java

where -d denote the destination and . represent the current location.


7. How to create a package in different location ?

You can create a package in different location using following commands:

javac -d C:// filename.java

8. How to run a package class code ?

You can run a package class using following commands:

java packagename.classname

9. How to bind more than one or multiple class in a single package ?

There are two way:

1. You can create all class inside single notepad and declare a package in top and create command .

        package a.b.c;
        public class A{

        }
        class B{

        }
        class C{

        }
    
Note: In this case you can make only one class as a public other class is default.

2. You can create seprate file for each class and make it public and declare the same package in all classes .

        //A.java
        package a.b.c;
        public class A{

        }
        //B.java
        package a.b.c;
        public class B{

        }
        //C.java
        package a.b.c;
        public class C{

        }
    
Note: In this case you can make all class as a public.

10. How many way to access package classes ?

There are four way:

  1. fully qualified name
  2. import a single class
  3. import a group of class
  4. static import

No comments: