Search code examples
javaantjavac

javac compilation issue with packages


Given this (game.Game.java, game.Player.java, game.io.InputConsole.java):

src  
|_game  
  Game.java  
  Player.java
  |_io
    InputConsole.java  

I've been trying to compile this project on console with javac (trying out various solutions found on SO and the internet) but I keep failing. I also tried using a batch file, but in either case, all I get are "cannot find symbol" errors.
Since almost all answers to related questions suggest to use a build tool like Ant or Maven, I decided to give it a try with Ant (first time). This is what my Ant file looks like:

<project default="run" name="Tic_Tac_Toe">
    <target name="run" depends="compile">
        <java classname="game.Main">
            <classpath path="bin" />
        </java>
    </target>
    <target name="compile">
        <javac srcdir="." destdir="bin"/>
    </target>
</project>

This is an excerpt of the output:

C:\Users\...\src\game\io\InputConsole.java:10: error: cannot find symbol
  public Player getPlayer(Sign sign) {

symbol: class Player
location: class InputConsole

PS: It works when I move InputConsole.java into the game package. So I'm sure the classes themselves are fine. I think the problem is either that I'm failing giving the compiler a proper path or my package structure is wrong.


Solution

  • You need to import in both. There is no hierarchy among packages and in spite of appearance game.io is not a "sub-package" of game, because there is no such thing as a sub-package.

    For classes in package game; you need import game.io.InputConsole;. In package game.io; you need import game.*;.

    Note that * is just convenience, it is probably better to import each referenced class individually.