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

前端 未结 4 1926
夕颜
夕颜 2020-12-11 09:19

I am supposed to do the following:

Write a Java application (Client) program with a static method called generateEmployees( ) that returns a random list

相关标签:
4条回答
  • 2020-12-11 09:30

    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 main and generateEmployees are both static, it should work. (If generateEmployees is non-static, you'd need to create an instance of the class first).

    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.

    0 讨论(0)
  • 2020-12-11 09:33

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

    Employee.generateEmployees(); 
    

    would do the trick.

    0 讨论(0)
  • 2020-12-11 09:45

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

    otherwise you'll need to do

     Employee.generateEmployees();
    

    (if the Employee class contains generateEmployees()

    0 讨论(0)
  • 2020-12-11 09:48

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

     public static void main(String[] args)
     {
          for(Employee employee: generateEmployees())
             print(employee); // define static print somewhere too
    
     }
    
    0 讨论(0)
提交回复
热议问题