简体   繁体   English

如何在同一个包中访问Java类

[英]How to access Java classes in same package

I have two java files (A.java + B.java) in src/com/example 我在src / com / example中有两个java文件(A.java + B.java)

A.java A.java

package com.example;

public class A {
    public void sayHello(){
        System.out.println("Hello");
    }
}

B.java B.java

package com.example;

public class B{
    public static void main(String... args) {
        A a = new A();
        a.sayHello();
    }
}

If I cd to one level above src and type javac -d classes src/com/example/B.java 如果我cd到src以上的一个级别并输入javac -d classes src / com / example / B.java

I get an error saying cannot find symbol A? 我收到错误,说找不到符号A?

javac doesn't know where to find source class you have to specify it with -sourcepath option. javac不知道在哪里找到源类,你必须用-sourcepath选项指定它。

See: 看到:

C:\example>mkdir src
C:\example>type > src/
C:\example>mkdir src\com\example
C:\example>more > src\com\example\A.java
package com.example;
public class A {
}
^C
C:\example>more > src\com\example\B.java
package com.example;
public class B {
    A a;
}
^C
C:\example>javac -d
C:\example>mkdir classes
C:\example>javac -d classes src\com\example\B.java
src\com\example\B.java:3: cannot find symbol
symbol  : class A
location: class com.example.B
        A a;
        ^
1 error
C:\example>javac -d classes -sourcepath src src\com\example\B.java
C:\example>

That's because Java doesn't know where to find the source of the other file. 那是因为Java不知道在哪里可以找到其他文件的来源。 You need to either cd into the src directory, or specify the src directory on the -sourcepath . 您需要cd进入src目录,或者指定-sourcepath上的src目录。

试试javac -d classes src / com / example / * .java

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Same Package java applet中的类 - Classes in Same Package java applet 如何访问默认包中的 java 类? - How to access java-classes in the default-package? Java +策略+工厂+相同的程序包=如何隐藏专门的类? - Java +Strategy + Factory + same package = how to hide specialized classes? 如何在Java中对同一包的类使用静态导入 - How to use static import on classes of same package in Java 如何在Java中创建对同一包中的其他类不可见的(私有)类? - How to make a (private) class in java that is not visible to other classes in the same package? Java类位于同一包(不同的目录)中,但它们不能彼此访问 - Java classes are in the same package (different directories) but they can't access each other 为什么Java中的“protected”修饰符允许访问同一个包中的其他类? - Why does the “protected” modifier in Java allow access to other classes in same package? 有什么方法可以在Java中定义一个私有类,只有同一包中的其他类才能访问它? - Is there any way to define a private class in Java which only other classes in the same package can access it? 在Java中的相同命名包中使用类 - Using Classes within the same named package in Java Java 同一文件夹中的类需要导入还是 package? - Java classes in same folder need import or package?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM