A Developer Gateway To IT World...

Techie Uncle Software Testing Core Java Java Spring C Programming Operating System HTML 5 Java 8 ES6 Project

Packages in java

What is the Packages in Java ?

What is the Packages in Java ?

Hello ! Guys lets understand the concept of packages in java.




Why Packages in java ?

The best answer: to avoid naming conflicts, and to control access or to make types easier to find and use methods (or function), variables and objects.

How to create packages?

Lets see to how to use packages in java?

package packageName;
we have to write package keyword above the class declaration in the code.


Consider the following code as example:






package package1;
public class name
{
 //code
}


 

From the above, you can understand that you have to create a class P1 in a folder like this:



we have created two folder named as package1 and package2 and there is a class in the PProject which is main class of the project.



In the package1, we have created two classes: H1 and P1.


In the package2, we have created  only one classes: P2.


See the all coding of all classes one by one:

package 1:  

P1.java codes are as follow:


package package1;
public class P1
{
   public void m1()
    {
        System.out.println("You are in the package 1");
    }
}


H1.java codes are as follow:


package package1;

public class H1
{
   public void m3()
    {
        System.out.println("You are in the package 1");
    }
}




package 2:  

P2.java codes are as follow:


package package2;
public class P2
{
   public void m2()
    {
        System.out.println("You are in the package 2");
    }
   
}


main class:

Now, consider the following java class which is inside the default package of your project; 
This is your main class since it contains main method and in the main method all methods like m1() from P1 class of package 1 and m2() from P2 class of package 2 are being called as below:


import package1.*;
import package2.*;
public class PProject {
    public static void main(String[] args)
    {
        P1 obj1 = new P1();
        H1 obj2 = new H1();
        obj1.m1();
        obj2.m3();
            
        P2 objP2 = new P2();
        objP2.m2();
    }
   
}






In the above example, we have to first import both packages like this:
import package1.*;
import package2.*;


It means classes P1, H1 and P2 are imported in main class PProject.
Now, user can make its object 
        P1 obj1 = new P1();
        H1 obj2 = new H1();
        P2 objP2 = new P2();
and by using these objects, methods can be accessed like as below:

obj1.m1();
obj2.m3();
objP2.m2();




sample output:

You are in the package 1
You are in the package 1
You are in the package 2



Types of package:


1. User-defined

2. Default

when you not create any package in the project, then class will be in the default package, otherwise. User-defined:)











LEARN TUTORIALS

.

.