********
1. In the case when the main function and the classes used are in the same directory:
Make a directory ./testpackage/
Make a java file with a class ./testpackage/MyObj.java
The directory name is equal to the package name.
----
package testpackage;
class MyObj {
private int i;
public MyObj( int _i) { i = _i;}
public int getI() { return i;}
public void setI( int _i) { i = _i;}
}
----
Make a java file with main() ./testpackage/MyCall.java
----
package testpackage;
import java.io.*;
import java.util.*;
import java.text.*;
public class MyCall {
public static void main( String[] args) {
MyObj obj = new MyObj( 10);
System.out.println( obj.getI());
changeInt( obj);
System.out.println( obj.getI());
}
public static void changeInt( MyObj obj) {
System.out.println("in changeInt, before change:" + obj.getI());
obj.setI( 20);
//obj = new MyObj( 20);
}
}
----
$ javac testpackage/*.java
$ ls testpackage
MyCall.class MyCall.java MyObj.class MyObj.java
$ java testpackage.MyCall
********
2. In the case when the main function and the classes used are NOT in the same directory:
Make a directory ./testpackage2/
Make a java file with a class ./testpackage2/MyObj.java
The directory name is equal to the package name.
Note: the class should be public to be used outside the package.
----
package testpackage2;
public class MyObj {
private int i;
public MyObj( int _i) { i = _i;}
public int getI() { return i;}
public void setI( int _i) { i = _i;}
}
----
Make a java file with main(): ./MyCall.java
----
import java.io.*;
import java.util.*;
import java.text.*;
import testpackage2.*;
public class MyCall {
public static void main( String[] args) {
MyObj obj = new MyObj( 10);
System.out.println( obj.getI());
changeInt( obj);
System.out.println( obj.getI());
}
public static void changeInt( MyObj obj) {
System.out.println("in changeInt, before change:" + obj.getI());
obj.setI( 20);
//obj = new MyObj( 20);
}
}
----
Now compile and run.
Note: classpath is the current directory which contains the package directory testpackage2.
$ javac testpackage2/*.java
$ ls testpackage2
MyObj.class MyObj.java
$ javac -classpath . MyCall.java
$ java MyCall