Java:在 main() 方法中调用静态方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16247687/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 22:23:09  来源:igfitidea点击:

Java: Calling a static method in the main() method

javastatic-methodsmainmethod-call

提问by Brittany Gefroh

I am supposed to do the following:

我应该做以下事情:

Write a Java application (Client) program with a static method called generateEmployees( ) that returns a random list of 10 different types of Employee objects. You could either use an array or an ArrayList to store the employee objects that will be returned. Use a for loop to populate randomly different types of employee objects with some random data. You could possibly think a range of values like 1 – 4. If random value is 1, create a HourlyEmployee object with some randomly generated data, if 2, SalariedEmployee object with some random data and so on. I would leave it to your ingenuity to generate and populate these different Employee objects. As these objects are generated add them to your data structure (array or ArrayList that you are using). Finally the method returns this data structure.

In the same application class, implement the main( ) method. Call the generateEmployees( ) static method and using a for loop print the details of each of the employee along with their earnings on the terminal window.

使用名为 generateEmployees() 的静态方法编写 Java 应用程序(客户端)程序,该方法返回 10 个不同类型的 Employee 对象的随机列表。您可以使用数组或 ArrayList 来存储将返回的员工对象。使用 for 循环用一些随机数据随机填充不同类型的员工对象。您可能会想到 1 – 4 之类的值范围。如果随机值为 1,则创建一个带有一些随机生成数据的 HourlyEmployee 对象,如果是 2,则创建带有一些随机数据的 SalariedEmployee 对象等等。我会把它留给你的聪明才智来生成和填充这些不同的 Employee 对象。在生成这些对象时,将它们添加到您的数据结构(您正在使用的数组或 ArrayList)中。最后,该方法返回此数据结构。

在同一个应用程序类中,实现 main() 方法。调用 generateEmployees() 静态方法并使用 for 循环在终端窗口上打印每个员工的详细信息以及他们的收入。

My generateEmployees() static method is as follows (it might not be correct... also, the data hasn't been randomly generated because I'm not exactly certain how to do that, at least as far as the first and last names are concerned.):

我的 generateEmployees() 静态方法如下(它可能不正确......此外,数据不是随机生成的,因为我不确定如何做到这一点,至少就名字和姓氏而言关心。):

public static Employee[] generateEmployees()
{
    Employee[] employees = new Employee[10];
    int randomNum = 0;

    for (int i = 0; i < 10; i++)
    {
        Random random = new Random();
        randomNum = random.nextInt(4) + 1;

         switch (randomNum)
         {
            case 0:
                employees[i] = new SalariedEmployee("Bri", "Gefroh", 123, 1000);
                break;
            case 1:
                employees[i] = new HourlyEmployee("Bri", "Gefroh", 123, 12.50, 10);
                break;
            case 2:
                employees[i] = new CommissionEmployee("Bri", "Gefroh", 123, 10000, 0.05);
                break;
            case 3:
                employees[i] = new BasePlusCommissionEmployee("Bri", "Gefroh", 123, 10000, 0.05, 2500);
                break;
         }
    }

    return employees;
}

How would I call this method and use it in the main() method? Each of those four types of employees are subclasses of the Employee class, and each subclass has its own toString() method, which is what I belivee I'm supposed to be outputting.

我将如何调用此方法并在 main() 方法中使用它?这四种类型的员工中的每一种都是 Employee 类的子类,每个子类都有自己的 toString() 方法,这就是我认为应该输出的方法。

回答by Scott Woodward

A static method is a class method, rather than an instance method. It's called on the class, not an instance of the class. The difference being that you can call a static method without having an instance first.

静态方法是类方法,而不是实例方法。它是在类上调用的,而不是类的实例。不同之处在于您可以在没有实例的情况下调用静态方法。

Employee.doSomething();

vs

对比

Employee employee = new Employee();
employee.doSomethingElse();

So, if your generateEmployees() method is in the same class as your main, all you need is

因此,如果您的 generateEmployees() 方法与您的主方法在同一个类中,那么您只需要

 generateEmployees();

otherwise you'll need to do

否则你需要做

 Employee.generateEmployees();

(if the Employee class contains generateEmployees()

(如果 Employee 类包含 generateEmployees()

回答by Ash

If the method is in the same class, you should just be able to call it like any other method:

如果该方法在同一个类中,您应该能够像调用任何其他方法一样调用它:

public static void main(String[] args)
{
    Employee[] employees = generateEmployees();

    // TODO: loop through and print out...
}

Since mainand generateEmployeesare both static, it should work. (If generateEmployeesis non-static, you'd need to create an instance of the class first).

由于maingenerateEmployees都是静态的,它应该可以工作。(如果generateEmployees是非静态的,则需要先创建该类的实例)。

I'd suggest having a constant array of Strings with "names" in it, and use a random number to generate an index. That should help with randomising the names a little.

我建议有一个常量数组,其中包含“名称”,并使用随机数生成索引。这应该有助于随机化名称。

回答by scottb

It's a static method, so ... it does not need to be accessed within the context of an instantiated object. You can just, you know, call it from your public static void main(...) method. If the class that contains your main() method is named Employee, then...

它是一个静态方法,所以......它不需要在实例化对象的上下文中访问。你知道,你可以从你的 public static void main(...) 方法中调用它。如果包含您的 main() 方法的类名为 Employee,则...

Employee.generateEmployees(); 

would do the trick.

会做的伎俩。

回答by Singagirl

Like Ash stated but if you need to process the records, here is no reason to introduce extra variable just do

就像 Ash 所说的那样,但是如果您需要处理记录,这里没有理由引入额外的变量,只是这样做

 public static void main(String[] args)
 {
      for(Employee employee: generateEmployees())
         print(employee); // define static print somewhere too

 }