piotr
piotr

Reputation: 61

How to access Java classes in same package

I have two java files (A.java + B.java) in src/com/example

A.java

package com.example;

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

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

I get an error saying cannot find symbol A?

Upvotes: 6

Views: 6613

Answers (3)

Buhb
Buhb

Reputation: 7149

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

Upvotes: 0

OscarRyz
OscarRyz

Reputation: 199224

javac doesn't know where to find source class you have to specify it with -sourcepath option.

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>

Upvotes: 5

Robin Green
Robin Green

Reputation: 33063

That's because Java doesn't know where to find the source of the other file. You need to either cd into the src directory, or specify the src directory on the -sourcepath.

Upvotes: 1

Related Questions