简体   繁体   中英

How to call a method from another class with no constructor

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?

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.

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); 

如果它是一个静态方法,你会做FactorialCalculator.factorial(...)

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!

First, you always have the standard constructor, which takes no parameters. So you can instatiate FactorialCalculator and then call its factoral -Method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM