How to call a method from another class without a constructor

I have problems with the program at school.

I need to call the factorial method in my FactorialCalculator class using the factorial method 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 create other methods, including the constructor.

Any suggestions?

+5
source share
5 answers

Create it as a static method:

 public class FactorialCalculator { public static int factorial(int number) { // Calculate factorial of number } } 

And you can call it that:

 int factorial = FactorialCalculator.factorial(5); // for the example 

A static method is a method that is not associated with any instance of any class, and can be accessed using the notation Classname.staticMethod () .. p>

+8
source

It's simple, if you make it Static , you can 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 that:

 int number = 10; int f = FactorialCalculator.factorial(number); 
+3
source

If this is a static method, you would do FactorialCalculator.factorial(...) .

+1
source

You can use the default constructor, which is simply FactorialCalculator fc = new FactorialCalculator(); . Easy. However, it seems your teacher wants you to create a static method. Static methods seem to be class utilities, not as an object function. So, in your case, you should make FactorialCalculator a utility class rather than an object class. public static int factorial(int num) {} should do the trick. So you can just go FactorialCalculator.factorial(5) , as it was in your example.

Hope this helps!

+1
source

Firstly, you always have a standard constructor that does not accept any parameters. So you can set the FactorialCalculator and then call its factoral-Method.

+1
source

Source: https://habr.com/ru/post/1237049/


All Articles