Trouble in invoking a method from one java class to another

I have a folder PackagesAndMethods . Within that folder I had two files

  1. TestMethods.java
  2. MyMethods.java

The code within those files are,

TestMethod.java

package PackagesAndMethods;

public class TestMethods
{
    public static void main(String args[])
    {       
        int result = MyMethods.Total();
        System.out.println(result);
    }
}

MyMethods.java

package PackagesAndMethods;

public class MyMethods
{
    public static int Total()
    {
        return 10;
    }
}

The problem is the "MyMethods.java" class compiles successfully but when compiling the "TestMethods.java", i am getting the bellow error

error: cannot find symbol
                int result = MyMethods.Total();
                             ^
  symbol:   variable MyMethods
  location: class TestMethods
1 error 

What I am doing wrong?

Jon Skeet
people
quotationmark

The problem is how you're compiling. You should generally be compiling from the "package root", ideally specifying an output root as well. For example, from the parent directory (D:\Java):

> javac -d classes PackagesAndMethods\MyMethods.java
> javac -d classes -cp classes PackagesAndMethods\TestMethods.java

Or more simply:

> javac -d classes PackagesAndMethods\*.java

Currently the compiler is expecting to find a directory called PackagesAndMethods to look in for classes in the PackagesAndMethods directory.

I'd personally separate the source into its own separate directory to keep it well away from the output, so you end up with:

> javac -d classes src\PackagesAndMethods\*.java

You're likely to find it simpler to start with if you work in an IDE which manages all of this for you though. It's still worth separating out the source and output.

people

See more on this question at Stackoverflow