简体   繁体   English

如何从没有构造函数的另一个类调用方法

[英]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. 我必须在我的FactorialCalculator类中通过一个名为factorial的方法在我的BCD类中调用一个名为factorial的方法。 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. 但是, factorialFactorialCalculator类中唯一的方法,我不允许再制作任何方法,包括构造函数。

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. 静态方法是一种与任何类的任何实例都无关的方法,可以使用Classname.staticMethod()表示法访问它。

It's Simple, if you make it Static , You will be able to call it from another class. 这很简单,如果你把它变成Static ,你就可以从另一个类中调用它。 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(); 您可以使用默认构造函数,它只是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. 因此,在您的情况下,您应该使FactorialCalculator更多地是实用程序类而不是对象类。 public static int factorial(int num) {} should do the trick. public static int factorial(int num) {}应该可以解决问题。 This way, you can just go FactorialCalculator.factorial(5) as you did in your example. 这样,你可以像在你的例子中那样去FactorialCalculator.factorial(5)

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. 所以你可以实例化FactorialCalculator ,然后调用它的factoral -Method

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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