views:

682

answers:

4

Possible Duplicate: How to access java-classes in the default-package?


Is it possible to import a class in Java which is in the default package? If so, what is the syntax? For example, if you have

package foo.bar;

public class SomeClass {
    // ...

in one file, you can write

package baz.fonz;

import foo.bar.SomeClass;

public class AnotherClass {
    SomeClass sc = new SomeClass();
    // ...

in another file. But what if SomeClass.java does not contain a package declaration? How would you refer to SomeClass in AnotherClass?

+12  A: 

You can't import classes from the default package. You should avoid using the default package except for very small example programs.

From the Java language specification:

It is a compile time error to import a type from the unnamed package.

Dan Dyer
Ah, great answer. Concise, correct, just enough detail, no extraneous information. I think that makes my last three answers from the JLS; it may be time to read it cover-to-cover.
Lord Torgamus
+2  A: 

The only way to access classes in the default package is from another class in the default package. In that case, don't bother to import it, just refer to it directly.

Dan
A: 

That's not possible.

The alternative is using reflection:

 Class.forName("SomeClass").getMethod("someMethod").invoke(null);
OscarRyz
That assumes the class is in a package in the CLASSPATH. If it were in the CLASSPATH, Eclipse would have found it and the trainees wouldn't have had to ask.
Kelly French
+1  A: 

As others have said, this is bad practice, but if you don't have a choice because you need to integrate with a third-party library that uses the default package, then you could create your own class in the default package and access the other class that way. Classes in the default package basically share a single namespace, so you can access the other class even if it resides in a separate JAR file. Just make sure the JAR file is in the classpath.

This trick doesn't work if your class is not in the default package.

Rob H