Packages in java

why packages?

  • Packages are used to group related classes and interfaces.
  • Classes with same name can be put into different packages.
  • A package is a collection of related types providing access protection.

how to create packages?

  • To create a package, you put a type (class, interface) in it.
  • To do this, a package statement at the top of the source file in which the type is defined.
  • For example, the following code appears in the source file pkg1.java and puts the SupA class in the pkg1 package:
package pkg1;
public class Emp
{		String name;
		Emp()
		{
		name="Learning2night.com";
		}
	void ShowNm()
	{	System.out.println("Hello "+name);
	}
}

Using package

 import pkg1.*;

class SomeClass
{
	public static void mian(String a[])
	{
		Emp e1= new Emp();
		e1.showNm();
	}
}

 

Add a Comment

Your email address will not be published. Required fields are marked *