There are two things you can do.
Either
(1) You can make fact
a static method, by putting the word static
after public
in its declaration.
Or
(2) You can make an object of the Looping
class and use it to run the calls to fact
, like this.
public static void main(String[] args) {
Looping looping = new Looping();
for(int i=0;i<=21;i++){
System.out.printf("%d!=%d\n", i, looping.fact(i));
}
}
It doesn't make any difference which you choose, because an object of the Looping
class doesn't have any fields, which means it doesn't carry around any data with it. It doesn't matter whether you make such an object or not; except for the fact that to use a non-static method, you need an object.
If the object had some fields, then a non-static method would be one that can refer to those fields. But since there are no fields, it makes no difference whether a method is static or not. Therefore, I'd probably choose option (1) here - just make the method static.
However, if, in the future, I want to have variations on the Looping
class - that is, subclasses, each with a slightly different implementation of the fact
method; then I really need to pick option (2). You can't really have different versions of a static method, within a subclass. When you write a class, you don't really know whether, in the future, you'll want some subclasses of it with slightly different behaviour. These may be subclasses that are going to be used in your program, or they may be things like mock subclasses that you use for testing.
Therefore, as a matter of course, it's always worth avoiding static methods. The only static method that any class ever needs to have is the main
method. Any other static methods are likely to cause you problems, as your program grows and you have more and more classes. Static methods can make testing harder. They definitely make it more difficult to implement polymorphism.
I realise that this argument might be beyond where your current Java knowledge is. But it would be worthwhile understanding what's happening in option (2), and getting into the habit of using it, rather than making all of your methods static by default.