A.Sha
A.Sha

Reputation: 155

java calling a class from another class within same package

So I was following this tutorial: https://spring.io/guides/gs/maven/

I cloned their repositories for the software for fear of mistyping something. The code does not work when I compile Greeter.java using javac and then use java to run HelloWorld.java file It gives me the following error:

HelloWorld.java:5: error: cannot find symbol
        Greeter greeter = new Greeter();
        ^
  symbol:   class Greeter
  location: class HelloWorld
HelloWorld.java:5: error: cannot find symbol
        Greeter greeter = new Greeter();
                              ^
  symbol:   class Greeter
  location: class HelloWorld
2 errors

I tried explicitly importing Greeter into HelloWorld using ìmport hello.Greeter The code works fine when I run it without the package hello;statements.

Any idea why I am getting this error??

So I followed through with the tutorial and using mvn package command and the jar file generated the project works.

So is this issue with trying to compile it with java command in the command line.

Adding directory structure of the project

pom.xml src     target

./src:
main

./src/main:
java

./src/main/java:
hello

./src/main/java/hello:
Greeter.java    HelloWorld.java


Upvotes: 1

Views: 81

Answers (1)

Lothar
Lothar

Reputation: 5449

I assume you try to compile the sources while you're in the directory src/test/java/hello. That's the wrong directory, you have to do it from directory src/test/java and pass the directory (i.e. package) to the compiler, e.g.

javac hello/*.java

Another reason might be that you haven't compiled Greeter.java, so the compiler doesn't find the class-file while compiling Hello.java. Above command should solve that.

If you have a main method in hello run java hello/name-of-file.java to run your main method.

Upvotes: 5

Related Questions