wholerabbit
wholerabbit

Reputation: 11536

Access static method from class in same package via. main()

I've never tried to do this before and am a little flummoxed. Two classes in the same package:

package test;

public class One {
    public static String test () { return "hello world"; }
}   

and:

package test;

public class Two {
    public static void main (String[] args) {
        System.out.println(One.test());
    }
}

If I try and javac Two.java inside the test/ directory, I get "cannot find symbol" for One. However, if I do it from the parent directory, javac test/Two, it compiles, and can then be run java test/Two -- but again not from inside (throws a NoClassDefFoundError saying the proper name of the class is test/Two, not Test).

Not a big deal, but curious if there is a better way around it, and if anyone can help me understand the issue. I actually do not need "Two" to be a formal member of the test package, I just need to have it in the same directory and compilable there.

Upvotes: 1

Views: 842

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1500215

You need to compile from the parent directory with:

javac test/Two.java test/One.java

(You might also want to use -d to say where you want the class files to end up. Note that you could just compile test/One.java and let the compiler find the class it depends on, but I find it cleaner to just specify all the source code you want to compile.)

And run with the package-qualified class name:

java test.Two

Upvotes: 3

Related Questions