0

Recently I have encountered some problem which seems a little strange to me.

In order to use some predefined class, I imported two .jar files say foo.jar and bar.jar(Both were written by others)

And my source code is like the following:

package jerry.deque
public class Deque {
    .....
    .....
    Foo item = new Foo();   //Already defined in the foo.jar
    .....
}

I added the external library exactly as what How to Import a Jar in Eclipse did. But when I tried to use the class defined in foo.jar Eclipse shows me that "Foo can't be resolved to a type".

I spent a lot of time to fix this problem and finally succeeded after I removed the clause: "package jerry.deque" at the beginning of my class file.

I think this is weird because just a few days ago when I was doing some Android development, I followed the same way to add a Twitter API library. And it works fine even when I declared "package jerry.search_twittes" at the beginning of my .java file. I'm confused by this problem and couldn't figure out what's going wrong. Could someone help me to explain it in detail? Thanks very much.

Community
  • 1
  • 1
Dreamer
  • 563
  • 1
  • 8
  • 25

2 Answers2

0

Check that Foo is same package as Deque class. If they are not same package, you need to import Foo class in Deque class.

For example,

package jerry.deque;
import packagename.foo; // packagename.foo
public class Deque {
    .....
    .....
    Foo item = new Foo();   //Already defined in the foo.jar
    .....
}

Added Explanation

I want you to check access modifier of Foo class carefully.

There are 2 access level for top level(class) access control . These are public, or package-private (no explicit modifier).

Your Foo class is under default package(not specified package)and may be no explicit access modifier. Hope so! Then, all classes under default package can access to Foo class. That's why when you remove package jerry.deque clause, it works.

Similarly, I want you to check Android development java code in which it works fine even when you declared "package jerry.search_twittes". In that case, classes inside Twitter API library's access modifier is public.So you can access it from anywhere.

For more information you can read this.Is this information helpful???

swemon
  • 5,840
  • 4
  • 32
  • 54
  • Then could you tell me why I succeeded in adding the Twitter API library? These two conditions seems very similar. What's the key that works for this problem..? – Dreamer Mar 14 '13 at 06:19
  • Sorry for the late acknowledge. I think it makes sense and thank you so much! – Dreamer Mar 14 '13 at 15:48
0

Foo is in default package. Classes from default package cannot be imported directly. So when you remove the package declaration in your code, you don't get the error. You can look for reflection api or write a proxy in the default package for that class.

Kishore
  • 819
  • 9
  • 20