Babanna Duggani
Babanna Duggani

Reputation: 727

Accessing class from different package in command line

I have created two folders in C:\Users\Documents folder. I have named the folders as A and B. Inside folder A, I have written below java class.

package A;

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

Inside folder B, I have below class written,

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. 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

Upvotes: 0

Views: 1272

Answers (1)

Bhargav Kumar R
Bhargav Kumar R

Reputation: 2200

You should be in the Documents folder to get access both the packages A & B while compiling Car class.

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.

To run the class Car use the below command.

java -cp . B.Car

While running Class with main(), you need to give full qualified path of class name i.e. packagename.className

Upvotes: 1

Related Questions