In this assignment we are illustrating how to import class in
other package.
In java , classes and interfaces can be grouped in packages.
Right click newly created java project and you will see option
new-> package as shown below.
create java project :packageDemo
Right click newly created project ( packageDemo ) select new->
select package
Click on package.
(enter package name eg: Package name :First) click on finish.
Right click the
package created (First). Add new class.
Following image
shows two packages created First (with class in it class1.java) and
Second (with class in it class2.java).
Add following code in Class1.java
package first;
public class class1 {
int num;
public void getdata(int id)
{
num=id;
System.out.println("getdata() of
Class1 from package first invoked");
}
public void display()
{
System.out.println(num);
}
}
create other package (eg: Package
name:second)
Right click package and add class .(eg:
class name class2)
Add following code in class2.java
package second;
import first.class1;
public class class2 {
public static void main(String args[])
{
class1 obj=new class1();
obj.getdata(4);
obj.display();
// obj.num=10;
}
}