Java package tutorial with example


Packages in java


What is packages?

A package is a grouping of related types providing access protection and name space management. Note that types refers to classes, interfaces, enumerations, and annotation types. 

A package is a collection of related classes.

It helps Organize your classes into a folder structure and make it easy to locate and use them.

More importantly, It helps improve re-usability.

 

Creating a class inside a package

           Create a directory structure as shown in image


 Main.java

public class Main

{

                // your code

}

Vehicle.java

                If your code belongs to package then your programs first line should be

                                package <packagename> 

package sam;

public class Vehicle
{
public  int a = 10
                //your code
}


Car.java

 package sam.test;

public class Car
{
                //your code
}


Accessing a class located in different package

There are two ways to access class located in another package

1.       Use import statement to access the class

 Star(*) imports all classes located in the package specified.

import sam.*; 

import sam.test.*;

 

But the best practice is to import only the specific class

import sam.Vehicle;

import sam.test.Car;

 

To access vehicle and car class in Main

 import sam.Vehicle;
import sam.test.Car;

class Main
{
	public static void main(String[] args)

	{
                Vehicle v1=new Vehicle();
                System.out.println(v1.i);
	}
}

 Compile all classes and run Main.java to check the output

 

2.      Instead of importing the class you can import it while creating the object

     sam.test.Vehicle v1=new sam.test.Vehicle(); 

   class Main
{
        public static void main(String[] args)

		{
			sam.test.Vehicle v1=new sam.test.Vehicle();
	                System.out.println(v1.i);
		}
}

This type of import will be used to avoid import conflicts when we have same class name in different package

© candidjava.com