简体   繁体   English

在命令行中访问来自不同包的类

[英]Accessing class from different package in command line

I have created two folders in C:\\Users\\Documents folder.我在 C:\\Users\\Documents 文件夹中创建了两个文件夹。 I have named the folders as A and B. Inside folder A, I have written below java class.我将文件夹命名为 A 和 B。在文件夹 A 中,我写在 java 类下面。

package A;

public class Food {
int a =6;
public int c = 10;
}

Inside folder B, I have below class written,在文件夹 B 中,我写了以下类,

package B;
import A.*;

public class Car {
 public static void main(String[] args) {
     Food food = new Food();
     System.out.println(food.c);         

 }
}

I am able to compile class Food from inside folder A. But when I am trying to compile class Car from inside folder B, I am getting below compilation error.我能够从文件夹 A 中编译类 Food。但是当我尝试从文件夹 B 中编译类 Car 时,我遇到了编译错误。 How to resolve this?如何解决这个问题?

Car.java:2: error: package A does not exist
import A.*;
^
Car.java:6: error: cannot find symbol
     Food food = new Food();
     ^
symbol:   class Food
location: class Car
Car.java:6: error: cannot find symbol
     Food food = new Food();
                 ^
symbol:   class Food
location: class Car
3 errors

You should be in the Documents folder to get access both the packages A & B while compiling Car class.在编译Car类时,您应该在Documents文件夹中以访问包 A 和 B。

And your compile statement must be something like你的编译语句必须是这样的

javac -cp . B/Car.java

Note: I put classpath as current directory(.) considering .class files are available under it.注意:考虑到 .class 文件在其下可用,我将类路径作为当前目录(.)。

To run the class Car use the below command.要运行类Car使用以下命令。

java -cp . B.Car

While running Class with main(), you need to give full qualified path of class name ie packagename.className使用 main() 运行 Class 时,您需要提供类名的完全限定路径,即packagename.className

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM