9 Packages
9 Packages
s
Introduction
//save as Simple.java
package mypack;
public class Simple{
public static void main(String args[])
{ System.out.println("Welcome to
package");
}
}
Accessing a Package
• There are three ways to access the
package from outside the package.
– import package.*;
– import package.classname;
class B{
public static void main(String args[]){
A obj = new A();
obj.msg(); Output: Hello
}
}
Using packagename.classname
//save by A.java
package pack;
public class
A{
public void
msg()
{System.out.
//save by B.java
println("Hell
package mypack;
o");}
import pack.A;
}
class B{
public static void main(String args[]){
A obj = new A(); Output: Hello
obj.msg();
}
}
Using fully qualified name
Note:
-d switch specifies the destination where to put
the generated class file;
d:/abc;
want to keep the package within the same directory, you
can use . (dot)]
• For java package program:
– You need to use fully name e.g.
qualified mypack.Simple etc to run
the class.
• To Compile: javac -d . Simple.java
Output: Hello
subpackage
Advantage of Java Package