Sunday, September 21, 2014

Import statement

Now let’s see how to use packages:

Import statement

Java has so many standard packages and programmers also create their own packages , but how can we use these in other programs. So we use import statement for this purpose.  In java import statement is used to import standard as user defined packages.  
Syntax:      import  packagename1 [ . packagename2 [ . packagename3 [ . packagenameN ]]]. (classname/*) ;

We can use particular class name or * sign. * sign import all the classes of the package if we use it.

Example:    import pk1.pkg2.a.java;       
                        OR    import pk1.pkg2.*;

Program : b.java

package up;    \\name of the package
import mypackage.*;     \\import all the classes of the mypackage package
class b{
          public static void main(String args[])
{
          A ob = new A(); \\ no need to use packagename.classname
          Ob.display(); \\
}
}


We have imported all the classes of the package mypackage. So now we can use the class members and methods by creating the entity (object) of the respective class. In the above example we have created an object ob of the class A and then we have used the method display() of class A as ob.display().

To run this program type command as:
Compile:    Javac –d . b.java        and press enter
Run:            java  up.b  


Remember: a java source file contain a single package statement and any number of import statement. And import statement must follow a package statement in java source file.

No comments:

Post a Comment