Hi there......
Java provides a mechanism for
partitioning the class name space into more manageable chunks.
This mechanism is the package. The package is both a naming and a
visibility control mechanism. You can define classes inside
a package that are not accessible by code outside that package.
To create a package is quite easy:
simply include a package
command as the first
statement in a Java source file. Any
classes declared within that file will belong to the
specified package. The package statement defines a name space in which
classes are
stored. If you omit the package statement, the class names are put into
the default
package,
which has no name.
- Package name must be saved in same name folder
- One package can comprise more than one class
- Java source code and class should be saved in same folder as package name
- One Java source file can include only one public class
- For make more than one class in same package every java source file must be saved in separate file
- Java source file class should be public visibility otherwise class'll not be available for outside of package
public class Myclass
{
public void show()
{
System.out.println("Package function");
}
}
when you will compile this file then it will create a class file named Myclass you must save this file in demo named folder.Ones everything gos ok then you are ready to use this file.. consider following code where i am using this...
import demo.Myclass ;
//import demo.*; for import all class in demo package
class MainFile
{
public static void main(String args[])
{
Myclass ob=new Myclass();
ob.show();
}
}
A package can be nested like java.awt.event as i discussed above that every package should be save in same name folder so you will have to a folder in your current folder named as you want for package
package demo.demo2;
public class Myclass
{
public void show()
{
System.out.println("Function from demo 2 package");
}
}
You must make a folder named demo2 in demo folder.You can make more nested package as you want you just have make a folder.When user will use such package they'll have to provide all heir achy of package in this case it will be
import demo.demo2.*;
class packdemo
{
public void show()
{
System.out.println("Nested package function");
}
}
- When you save this package in Bin folder then you can use (javac) for compile
- If your package folder is outside of bin folder then you can use ( javac -classpath <java sourcefile>)
- -classspath will search your package class file
No comments:
Post a Comment