So I just started with Java a few weeks ago and I am trying to teach myself how to make my own methods. I made a program that adds two numbers when I compile the class “ClassTest”. Here is the error:
H:\Java Things\ClassTest.java:10: error: cannot find symbol
GetNum(int1, int2);
^
symbol: method GetNum(int,int)
location: class ClassTest
1 error
Process completed.
Here is the code for ClassTest:
import LotsOfMethods.*;
public class ClassTest
{
public static void main (String[] args)
{
int int1 = 5, int2 = 7;
GetNum(int1, int2);
}
}
And here is the code for ExampleMethod:
package LotsOfMethods;
public class ExampleMethod
{
public static int GetNum(int num1, int num2)
{
int result;
result = num1 + num2;
return result;
}
}
First, it’s important to recognize how you call a method in Java. You need to specify the object who will fulfill the method, and the name of the method that you’re calling.
When you write:
You’re not specifying an object that will execute GetNum. Java has some default behavior to handle this case: it tries to resolve the method from the object context surrounding your code. So Java says, “I can’t find a GetNum() method belonging to this ClassTest object,” and you get the error:
The method that you want is in the class ExampleMethod. It is a static method attached to the ExampleMethod class, which means you don’t need to instantiate a copy in order to get there. Instead, you can do:
Classes with static methods provide a sort of namespace around those methods, and so the class itself provides enough data to resolve your method. If you had a non-static method, you’d need to do something like:
I hope this helps.