What is the syntax for importing a class into a default package in Java?

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 do you feel about SomeClass in AnotherClass ?

+42
java syntax import
Jan 08 '10 at
source share
5 answers

You cannot import classes from the default package. You should avoid using the default package, with the exception of very small sample programs.

From the Java language specification :

This is a compilation to import a type from an unnamed package.

+83
Jan 08 2018-10-10 at
source share
β€” -

The only way to access classes in the default package is from another class in the default package. In this case, do not bother importing, just access it directly.

+22
Jan 08 '10 at 19:37
source share

It's impossible.

An alternative is to use reflection:

  Class.forName("SomeClass").getMethod("someMethod").invoke(null); 
+10
Jan 08 '10 at 19:40
source share

This is not a compilation error! You can import the default package only into the default package class.

If you do this for another package, it will be a compilation error.

+2
Aug 11 '13 at 9:11
source share

As others have said, this is bad practice, but if you have no choice, because you need to integrate with a third-party library using the default package, then you can create your own class in the default package and thus access another class. Classes in a package by default mostly use one namespace, so you can access another class even if it is in a separate JAR file. Just make sure the JAR file is in the classpath.

This trick does not work if your class is not in the default package.

+1
Jan 08 '10 at 19:45
source share



All Articles