public class square
{
public int squareNum(int number)
{
return (number*number);
}
public static void main(String[] args)
{
int num = Integer.parseInt(args[0]);
int square = squareNum(num);
System.out.println(square);
}
}
the compiler complains about the 'squareNum'method not being static. If
I make it static it works fine, but in sme cases I would not be able to
make the method static.
In this example, which is common, "main" is not a method of any object.
No "Square" object is ever created. Because there's no object in
memory, there's no "squareNum()" method either. It's been declared, but
since it's a regular (volatile) method, it cannot run without an
instance of the class it lives in.
Two ways to work around this.
You could make an instance of Square inside your main method,
and then call squareNum() on that instance you made:
<code>
public class Square
{
public int squareNum(int number)
{
return (number*number);
}
public static void main(String[] args)
{
Square squareInstance = new Square();
int num = Integer.parseInt(args[0]);
int squareValue = squareInstance.squareNum(num);
System.out.println(squareValue);
}
}
</code>
Another way to work it, is to make squareNum() a static method,
and then you can call it directly without making an instance of the
Square object.
public static int squareNum(int number)
//...
int squareValue = Square.squareNum(num);
Of course, if you don't want the exercise, you could just do
int squareValue = (int) Math.pow(num, num);
Notice that Math.pow() is a static method -- it's not necessary to
create a "Math" object in order to call that method.
"main" is confusing, since it's inside the class you want to use, but
you have to understand that it's a static method and that there is no
Object -- and that even if there *was* an Object, main would not know
about it.
You've made a couple of poor choices of identifiers: In Java, it is
suggested that class names start with an upper case letter. That's not
enforced, but it is almost universally followed. But also, you've used
another identifier (int square) for a variable that's within the scope
of a class by the same name (square), which is the sort of thing that
leads to desperate confusion if it goes too far.
What is the best way to create methods outside of the 'main' method that
are to be called in main?
That depends on what you're doing. Usually the most appropriate
approach is to make regular methods, and then create an Object in main,
and call the methods on that object. But there are certainly many
situations where static methods are called for.
Most often, there is data in an object that you want a method to
manipulate, and in order for that to work, you need regular methods, and
an object instance.
The whole issue why is confusing
Static stuff is in the *Class*, and dynamic stuff is in the *Object*.
Once you get your brain around that distinction, it won't be confusing
anymore.