• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

static

 
Jimmian Lin
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I was wondering why in the following code for factorial, I needed to declare the factorial and iter methods static.


public class example_fact2{
public static void main(String[]args){
System.out.println(factorial(7));
}
public static int factorial(int n){
return iter(1, 1, n);
}
private static int iter(int counter, int product, int n){
if(counter> n){
return product;
}
else{
return iter(counter+1, product*counter, n);
}
}
}
 
Juva Yuva
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Juva Yuva:


Thats because you declared the method (factorial) as Class method. And since main is static , methods can be called directly . Otherwise It can be accessed in non-static way , by creating instance of the class.

1) Try creating an instance of the class in the main method , call the factorial method with the instance.
2)And remove the static modifiers from the methods
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic