1. Not finding help here? Sign up for a free 30min tutor trial with Chegg Tutors
    Dismiss Notice
Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Apply a non-static method in a static context

  1. May 27, 2012 #1
    1. The problem statement, all variables and given/known data

    Very simple problem; I have three classes, Company, CompanyTest, and Employee. CompanyTest gets a bunch of information together about an employee, like salary, address, etc., and then it creates an Employee object using the Employee class. Great, so I have successfully asked the user for information, and an Employee object, let's call it emp, has been created.

    Now in Company class, I have an ArrayList (obviously dynamic) that will keep a list of all the employees. In Company, I also have the following method:

    Code (Text):
    public ArrayList<Employee> list = new ArrayList<Employee>();
       
        public void addEmployee(Employee person)
        {
            list.add(person);
        }
    Finally, in CompanyTest, I want to add this object emp by saying

    Code (Text):
    Company.addEmployee(emp);
    in CompanyTest. So I'm trying to add emp to the list of employees, and each Employee object will be created in Employee class.

    I keep getting the error:

    Code (Text):
    CompanyTest.java:49: non-static method addEmployee(Employee) cannot be referenced from a static context
                    Company.addEmployee(emp);
                                           ^
    1 error
    So my question is: how do I add an employee to this list that is created in Company class??? This is getting very annoying as it is a very simple task that a computer can't seem to get.

    Thanks in advance.

    2. Relevant equations



    3. The attempt at a solution
     
  2. jcsd
  3. May 27, 2012 #2
    Basically I'm trying to figure out how to call a method that uses an ArrayList.
     
  4. May 28, 2012 #3

    HallsofIvy

    User Avatar
    Staff Emeritus
    Science Advisor

    How, exactly, are you using this? You appear to be defining a type "company" that contains an employee list. But that means that a specific company has a employee list. You cannot access an employee list from the "company" type. That is what is meant by a "non-static" method. You would have to declare a variable like:
    Company FredsComputerRepair;

    and then FredsComputerRepair.addEmployee(Harold).
     
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook




Similar Discussions: Apply a non-static method in a static context
Loading...