Reputation: 53
I'm having a bit of trouble on a program at school.
I have to call a method called factorial
in my FactorialCalculator
class through a method called factorial
in my BCD
class. Normally, I would do something like this:
FactorialCalculator newCalc = new FactorialCalculator(8);
However, factorial
is the only method in the FactorialCalculator
class, and I am not allowed to make any more methods, including a constructor.
Any suggestions?
Upvotes: 5
Views: 3281
Reputation: 422
First, you always have the standard constructor, which takes no parameters. So you can instatiate FactorialCalculator and then call its factoral-Method.
Upvotes: 1
Reputation: 17132
Create it as a static method:
public class FactorialCalculator {
public static int factorial(int number) {
// Calculate factorial of number
}
}
And you can call it this way:
int factorial = FactorialCalculator.factorial(5); // for the example
A static method is a method that is not associated with any instance of any class, & it can be accessed using the Classname.staticMethod( ) notation.
Upvotes: 10
Reputation:
You can either use a default constructor, which is just FactorialCalculator fc = new FactorialCalculator();
. Easy as that. However, it looks like your teacher wants you to create a static method. Static methods are sort of like utilities of a class, instead of being a function of an object. So, in your case, you should make FactorialCalculator be more of a utility class instead of an object class. public static int factorial(int num) {}
should do the trick. This way, you can just go FactorialCalculator.factorial(5)
as you did in your example.
Hope this helps!
Upvotes: 1
Reputation:
It's Simple, if you make it Static
, You will be able to call it from another class.
Create it as a static method:
class FactorialCalculator {
public static int factorial(int number) {
...YourCode...
}
}
And you can call it this way:
int number = 10;
int f = FactorialCalculator.factorial(number);
Upvotes: 4
Reputation: 9093
If it is a static method, you would do FactorialCalculator.factorial(...)
.
Upvotes: 1