gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 07:17:23 26 4
gpt4 key购买 nike

我应该做以下事情:

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() 静态方法如下(它可能不正确......另外,数据不是随机生成的,因为我不确定如何做到这一点,至少就第一个而言和姓氏有关。):

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

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

最佳答案

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

Employee.doSomething();

对比

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

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

 generateEmployees();

否则你需要做

 Employee.generateEmployees();

(如果 Employee 类包含 generateEmployees()

关于Java:在 main() 方法中调用静态方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16247687/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com