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?
If we don't define a constructor in a class, then the compiler creates a default constructor(with no arguments) for the class. And if we write a constructor with arguments or no arguments then the compiler does not create a default constructor.
We can call a static method by using the ClassName. methodName. The best example of the static method is the main() method. It is called without creating the object.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With