Package demo:
Creating a user define package
- A package is a folder having related set of classes
- Two packages can have classes with same name
- Such packages get placed into some folder on some driver
- It works as a library for any project
Steps
- Create a folder as container of your packages
- d:\mypackages
- Think your package names and created sub folders with those names under your container folder
- E.g. p1 and p2
- Create your classes and place them into these folders
- Each class must have package command on top
Example
Create a class as General having some general methods like SquareRoot, CubeRoot and place it into p1 package
Create another class as Sample in package p2 having some sample method like Hi(), Hello()
Create a class UsingPackage where input a number from keyboard and print square root and cube root of that number using the class General of p1 package.
Note: To search the classes inside the packages, we need to define the CLASPATH
CLASSPATH is an environment variable to search the class files
For Kawa
Packages à classpath à Add Dir… à Select the folder name having the packages
D:\mypackages
For DOS
- Set the CLASSPATH using
o SET CLASSPATH=%CLASSPATH%;d:\mypackages;
For NetBeans
- Select Libraries Properties
§ Add Jar/Dir…
Note:
Remember every properties of classes,methods,packages etc. otherwise you can find such types of errors:
1.--------------------------- Compiler Output ---------------------------
UsingPackage.java:1: package p1 does not exist import p1.*; ^ UsingPackage.java:11: cannot find symbol symbol : variable MyClass location: class UsingPackage System.out.println("Square root is : "+MyClass.square(n)); ^ 2 errors
2. --------------------------- Compiler Output ---------------------------
UsingPackage.java:11: square(int) is not public in p1.MyClass; cannot be accessed from outside package System.out.println("Square root is : "+MyClass.square(n)); ^ 1 error
3. --------------------------- Compiler Output ---------------------------
UsingPackage.java:11: square(int) is not public in p1.MyClass; cannot be accessed from outside package System.out.println("Square root is : "+MyClass.square(n)); ^ 1 error
Tweet