What's the syntax to import a class in a default package in Java?

JavaSyntaxImport

Java Problem Overview


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?

Java Solutions


Solution 1 - Java

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.

Solution 2 - Java

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.

Solution 3 - Java

That's not possible.

The alternative is using reflection:

 Class.forName("SomeClass").getMethod("someMethod").invoke(null);

Solution 4 - Java

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.

Solution 5 - Java

It is not a compilation error at all! You can import a default package to a default package class only.

If you do so for another package, then it shall be a compilation error.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionPopsView Question on Stackoverflow
Solution 1 - JavaDan DyerView Answer on Stackoverflow
Solution 2 - JavaDanView Answer on Stackoverflow
Solution 3 - JavaOscarRyzView Answer on Stackoverflow
Solution 4 - JavaRob HView Answer on Stackoverflow
Solution 5 - Javavishal rajputView Answer on Stackoverflow