1

I have a class file located somewhere on the filesystem. It doesn't have a package declaration (was created in default package).

Now I want to use that class file in a package. I added the class folder in the build path, but eclipse can not find it.

package test;

public class Test1{
    public static void main(String[] args){
        ExternalClass.print(); // ExternalClass cannot be resolved.
    }
}

If I move "Test1" to the default folder, everything works fine:

public class Test1{
    public static void main(String[] args){
        ExternalClass.print();
    }
}

How can I use "ExternalClass" in the package "test" ?

user
  • 211
  • 2
  • 12
  • http://stackoverflow.com/questions/283816/how-to-access-java-classes-in-the-default-package . This solves my problem, but other answers are appreciated ;) – user Dec 03 '13 at 03:19

2 Answers2

1

As per http://mindprod.com/jgloss/import.html it is not possible to use classes in the default package from a named package.

Prior to J2SE 1.4 you could import classes from the default package using a syntax like this:

import Unfinished;

That's no longer allowed. So to access a default package class from within a packaged class requires moving the default package class into a package of its own.

If you have access to the source , some post-processing is needed to move the file into a dedicated package and add this "package" directive at its beginning.

Scary Wombat
  • 44,617
  • 6
  • 35
  • 64
0

Default scope limits the scope of a class file to same directory itself. To achieve what you need do these steps,

  1. Import that External class in a class, which will have same directory with external class
  2. Give a proper package name for class in which you imported.
  3. Use this new class to make a call to external class, and import this anywhere in program based on your package name.
Abhishek Anand
  • 1,940
  • 14
  • 27
  • I don't get the first two steps. Could you explain them further ? The new class file needs a package declaration. Therefore it can not find the "ExternalClass" – user Dec 03 '13 at 03:00