Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call a method from another class with no constructor

Tags:

java

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?

like image 966
fufupug Avatar asked Nov 29 '15 15:11

fufupug


People also ask

What happens if there is no constructor method in a class?

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.

How do you call a method from another class without creating an object?

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.


1 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 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.

like image 95
Mohammed Aouf Zouag Avatar answered Sep 30 '22 03:09

Mohammed Aouf Zouag