Putting java code in packages (subdirectories)
The "package" statement
Every java class is part of some package. Essentially, the package is the same as the directory the .java file lies in. The first line of every java class needs to state the package name.

Dir/SubDir/ExampleClass.java
package Dir.SubDir;

public class ExampleClass { 
    ...
}
The "import" statement
If two classes are in the same package (directory), then they can access each other freely. Otherwise, you need to add an "import" statement to allow one to access the other. For example suppose the class in the file AnotherDir/AnotherClass.java wants to access Dir/SubDir/ExampleClass.java. It's java file might look like:
AnotherDir/AnotherClass.java
package AnotherDir;

import Dir.SubDir.ExampleClass;

public class AnotherClass { 
    ExampleClass ec=new ExampleClass();
    ...
}
In case a java file wants to access every java class in a certain package, you can use the "import" statement:
import Dir.SubDir.*;
An annoyance
Unfortunately, java is picky about variable access when classes are in different packages. Take the following example, which will produce errors:
DirA/ClassA.java
package DirA;

public class ClassA {
	int n=10;
}
DirB/ClassB.java
package DirB;

import DirA.*;

public class ClassB {
	ClassA a;
	
	public void printA() {
		System.out.println("The value of a.n is "+a.n);
	}	
}
You could try to compile ClassB using the command "javac DirB/ClassB.java". This will result in an error:
DirB/ClassB.java:9: n is not public in DirA.ClassA; cannot be accessed from outside package
                System.out.println("The value of a.n is "+a.n);
                                                                                 ^
1 error
The solution should be evident from the error message. You need to make the variable "n" public. So the following will compile correctly.
DirA/ClassA.java
package DirA;

public class ClassA {
	public int n=10;
}
DirB/ClassB.java
package DirB;

import DirA.*;

public class ClassB {
	ClassA a;
	
	public void printA() {
		System.out.println("The value of a.n is "+a.n);
	}	
}
back to McBilliards' Developer Documentation or McBilliards' SourceForge website
SourceForge.net Logo Valid Valid CSS!