Q) With respect to accessing static content, what is the difference between user defined package and java system package (say java.lang etc)
I'm preparing for ocjp6. using 1.6.26 java version
my java program has a package named "pack" in PackageTest.java
package pack;
public class PackageTest {
public static final int i=20;
}
}
javac -d . PackageTest.java
created PackageTest.class file in pack folder
now accessing static contents of PackageTest class from another java
program (TestStaticContents.java) as below
import pack.PackageTest.*;
// here importing all contents of PackageTest class
class TestStaticContents {
public static void main(String[] args){
System.out.println("normal import, accessing i value with class name: "+PackageTest.i);
}
}
javac TestStaticContent.java
displaying Compilation Error:
TestStaticContents.java: cannot access PackageTest bad class file: .\PackageTest.java
If i try accessing static contents of Math class from my java program its not displaying any compilation error i.e
import java.lang.Math.*;
// here importing all contents of Math class
class TestMathStaticContents {
public static void main(String[] args){
System.out.println("normal import, accessing pi value with class name : "+ Math.PI);
}
}
javac TestMathStaticContents.java
No Compilation Error, and PI value is printed as expected.
Why this behavior is different compared to User defined package?
I believe I understand your problem now. You've placed both
PackageTest.javaandTestStaticComponents.javain the same package,pack. Two classes that share the same package cannot explicitly import one another.You've hinted at this yourself by providing
TestStaticComponents.javawith a package-private class identifier.Your import statement works perfectly if both classes reside in different packages.