java packages: cannot find symbol

后端 未结 2 524
鱼传尺愫
鱼传尺愫 2020-12-06 08:14

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

相关标签:
2条回答
  • 2020-12-06 08:47

    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.

    0 讨论(0)
  • 2020-12-06 08:52

    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();
        }
    }
    
    0 讨论(0)
提交回复
热议问题