4

I'm having a strange error. I have 2 classes in the same package but they can't find each other. From what I remember, as long as the classes are in the same package, they should be able to call each other's methods.

My code looks similar to this:

in A.java:

package com.mypackage;
public class A{
   public static int read(){
    //some code
   }
}

in B.java:

package com.mypackage;
public class B{
  public static void main(String args[]){
    int x = A.read();
  }
}

and it's giving me a cannot find symbol variable A error.

Both of these classes depend on some .jar files, but I've already included the path of those jars to CLASSPATH and A.java compiled fine, but B can't find A for some reasons...

When I remove the package com.mypackage; in both classes then they compile fine.

Sled
  • 18,541
  • 27
  • 119
  • 168
Dao Lam
  • 2,837
  • 11
  • 38
  • 44

2 Answers2

5

Since you're compiling Java files that are in distinct packages, you'll have to ensure that they compile to the appropriate directories.

You can use this invocation to do just that. Substitute $SRC with the location of your source files, and you can let $BIN be the current directory, or some other location on your machine.

javac -sourcepath $SRC -d $BIN A.java B.java

When you want to run them, you have to add them manually to the classpath again (but that's not such a bad thing).

java -cp $BIN com.mypackage.B

This invocation should work; just made sure of it with A.java and B.java residing on my desktop. With the -d flag, that ensured that when they compiled, they went to the appropriate package folder scheme.

Makoto
  • 104,088
  • 27
  • 192
  • 230
  • 1
    It works! Thank you! I compiled the way you suggested. But when I ran it, I had to include the path of the jar files as followed (with $LIB as the path of my jars): `java -cp $BIN:$LIB com.mypackage.B` I'm surprised it didn't require me to do that when I compiled... – Dao Lam Jul 17 '12 at 18:15
  • I presume that the reason you didn't need them while you were *compiling* was due to them already present in your classpath. If they weren't, it would've been a matter of setting `-cp $LIB` while compiling. – Makoto Jul 17 '12 at 21:03
3

It should be:

A.java

package com.mypackage;
class A {
    public static int read(){
       //some code
    }
}

B.java

package com.mypackage;
class B {
    public static void main(String args[]){
       int x = A.read();
    }
}
Makoto
  • 104,088
  • 27
  • 192
  • 230
Jyro117
  • 4,519
  • 24
  • 29
  • Yea sorry I was in a rush and forgot to include that in my post. I just edited it. Can you take a look again? – Dao Lam Jul 17 '12 at 17:47