what is the difference between user defined package and system defined java package with respect to accessing static content

1k views Asked by At

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?

2

There are 2 answers

10
Jacob G. On

I believe I understand your problem now. You've placed both PackageTest.java and TestStaticComponents.java in 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.java with a package-private class identifier.

Your import statement works perfectly if both classes reside in different packages.

0
Vince On

import java.lang.Math.* attempts to import the nested types from Math, not the static members. You should be using import static:

import static java.lang.Math.PI; //recommended to avoid wildcards

When using imported static members, you do not need to reference the class when using the member: You can use PI instead of Math.PI.

No Compilation Error, and PI value is printed as expected.

This is because java.lang.Math, like all types in the java.lang package, is automatically imported: there's no need to import it. Because of this, Math.PI isn't causing an error like you'd expect.

If you used PI instead of Math.PI, you would have gotten an error, informing you the static member wasn't imported.