Multiple classes, arrays, static, non-static issues

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Jimmysevens
    New Member
    • Apr 2010
    • 5

    Multiple classes, arrays, static, non-static issues

    Hi there, I'm new to java and would appreciate help with this.

    My project involves me creating 5 classes; Person, Employee, Demonstrator, Payroll and Test.

    Employee and demonstrator are inherited from person. Data is read in from 2 seperate text files for each of these.

    Test contains the main() method

    Payroll contains an array of Person (the monthly payroll), and contains methods to add or remove employees/demonstrators from the payroll.

    There are various other methods/minor details but I don't think they affect my query.


    Anyway, I've spent quite a few hours at this and have figured out most of it, but there's one fundamental thing which I'm having trouble with and that's static and non-static methods. I create multiple employees and demonstrators using a for loop and array in both Employee and Demonstrator, but I'm not sure whether this should be a static method, as when I used a static method, and then used payroll with static methods it all seems to work but from what I've been reading on Google/various forum this is probably wrong.

    When I use a non-static method I use a getEmployeeArra y() method which just returns the array. But I don't really know how refer to this in the payroll class. Whereas when the methods in Payroll and this one in Employee are static I can just use Employee.getEmp loyeeArray().

    If anyone could shed some light it would be greatly appreciated. I'd paste all my code but I now have 3 different versions depending on which you say is the right way to go about it.

    Thanks, in advance!
  • jkmyoung
    Recognized Expert Top Contributor
    • Mar 2006
    • 2057

    #2
    It sounds like you have a static list of all instances inside each class, correct?

    non-static functions should be used when you're asking a particular member of the class to do something, or tell you something.

    Eg: if you want to know the height of an employee, that would be a non-static call to 1 specific employee. Every employee will return something different. Since you seem to be using a static list,

    - If you wanted to calculate the average height of all employees, you would run a static function.
    - This static function would access the static list.
    - When looking at each employee in the list, the function would call the non-static function height() for each employee.

    The part that makes it confusing is that you have the static list within the class itself. If that list were just an array in some other class, then it would be much easier to tell which functions were static and which weren't.

    Comment

    • Jimmysevens
      New Member
      • Apr 2010
      • 5

      #3
      Here is the code for the parts of the person class I think are relevant, (version of readinfo() that is non-static).
      Code:
      import java.util.*;
      import java.io.*;
      
      public class Employee extends Person 
      {           
          private double salary;
          public Person[] employ = new Person[15];
              
          public Employee (String f, String l, String d, String n, int t, double s)
          {
              super(f,l,d,n,t);
              salary = s;
          }        
          
          public void readinfo() throws FileNotFoundException
          {     
              Scanner inFile = new Scanner(new FileReader("EmployeeData.txt"));
               for (int i=0; i<inFile.nextInt(); i++)
                  {
                      employ[i]= new Employee(inFile.next(), inFile.next(), inFile.next(), inFile.next(), inFile.nextInt(), inFile.nextDouble());
                    }
              }   
               
              public Person[] getarray()
              {
               return employ  ;
              }
          
          public void showDetails()
          {
              super.showDetails();
              System.out.println ("Salary = " + salary + "\n");
          }
      And heres part of my payroll class with a method which is still static, as I don't really know how to do it otherwise (even though it's not working now that readinfo() is non-static.

      Code:
      public class Payroll()
      public static void showempDem() throws FileNotFoundException
      {
          Person[] employees = Employee.readinfo();//This isnt getarray() because when static readinfo() was used to return array as it meant I could get the size of the array from the text file.//
          System.out.println("----------EMPLOYEES:----------");
          
          for (int i = 0; i<employees.length; i++)
          {
              System.out.println(i);
              employees[i].showDetails()
          }
       }
      The problem therefore is that I'm unsure how to access the objects being referenced by the array in Employee, in Payroll. OR the problem is whether it is ok to use readinfo() and payroll as static (which from googling and your answer it looks like it's not).

      The bit which has confused me really is that I've got an array object which references Employee objects. And to reference the employees i need to reference the array, which is only there as there was no other way (for me) to make multiple employees from a textfile. If I can just find out how to reference that employee array in Payroll, in a non-static method I think I'd be fine now. Though it was lovely when the entire thing was working with statics :(.

      Cheers for the help.

      Comment

      • jkmyoung
        Recognized Expert Top Contributor
        • Mar 2006
        • 2057

        #4
        Let's go through this field by field.
        1. public double salary.
        Every employee has a different salary, so I'm pretty sure this is correct.

        2. public Person[] employ = new Person[15];
        Are you saying each employee has 15 Person's under them? If not, it should be static. You probably also want: new Employee[15] instead.

        3. definitely static, since it uses the same file to get input from. -> Means #2 must be static, (unless all employes have the same 15 person's under them.)

        4. getArray. depends on 2.

        5. showDetails() . depends on salary. Must be non-static.
        ===
        The array should either be static, or not in this class.
        Setting it up in this static method really limits the use of your class though, as you can only ever have maximum 15 listed People.

        Ideally, there would be another class, say Company, that contained the array of People.

        Comment

        • Jimmysevens
          New Member
          • Apr 2010
          • 5

          #5
          Sorry my use of words in the coding is a bit confusing. I used that to just make an array which can hold 15 people (I realise it should have been employees now). It doesnt mean people have 15 people that they employ. Before I changed it to non-static it looked like this:
          Code:
          public class Employee extends Person 
          {           
              private double salary;
                  
              public Employee (String f, String l, String d, String n, int t, double s)
              {
                  super(f,l,d,n,t);
                  salary = s;
              }        
              
              public static void readinfo() throws FileNotFoundException
              {     
                  Scanner inFile = new Scanner(new FileReader("EmployeeData.txt"));
                  public static Person[] employ = new Employee[inFile.nextInt];
                  for (int i=0; i<employ.length; i++)
                 {
                      employ[i]= new Employee(inFile.next(), inFile.next(), inFile.next(), inFile.next(), inFile.nextInt(), inFile.nextDouble());
                 }
          
                 return employ;
              }   
              
              public void showDetails()
              {
                  super.showDetails();
                  System.out.println ("Salary = " + salary + "\n");
              }
          I just used employ instead of employees, basically everyone is either an employee (yearly salary) or demonstrator (monthly salary) slightly different classes, The spec explains it better.

          the spec says this:
          " A new University has commissioned you to write a payroll program to pay its staff and practical class demonstrators. The following classes are required:

          Person class: Store the various information(edi ted out)

          Employee class should, in addition to the previous information, store the annual salary for the employee.

          Demonstrator class should store the number of hours worked by the demonstrator and their hourly rate (demonstrators are paid per hour worked and do not have a fixed annual salary).

          Provide methods in these classes to read in Employee information from a file “EmployeeData.t xt” and demonstrator information from a file “DemonstratorDa ta.txt” . You are responsible for defining the format of these files.

          Payroll class stores an array of Person and provides methods to add and remove a Person from the payroll. Write a method runPayrollMonth ly to calculate the monthly pay and tax for each person on the payroll (you should write a method calculateTax() in both the Employee and Demonstrator classes which actually performs the calculation."

          I have taken this to mean that i have to read in (and therefore create the employee and demonstrator objects) in their own classes. And if i understand you, that therefore means it should be static?

          Also should any of payroll be static, as I personally think it does, but my judgement is not brilliant due to me being quite new to java. thanks.!

          Comment

          • jkmyoung
            Recognized Expert Top Contributor
            • Mar 2006
            • 2057

            #6
            "Payroll class stores an array of Person"
            Not sure how much of it is due to incorrect cutting and pasting, but it should be:
            Code:
            class Payroll {
              public Person[] employ = new Person[15]; 
             
              public static void readinfo() throws FileNotFoundException 
                {   
              ... 
              }
            Move those out of Employee and into Payroll.
            The key is really how you want to treat Payroll. If you only ever want to have one payroll, make the class static, and all the functions static.

            If you want to be able to have multiple Payrolls at once, make everything in the class non-static.

            Comment

            • Jimmysevens
              New Member
              • Apr 2010
              • 5

              #7
              Hmmm ok, thanks for your prolongued patience! From what the spec says it seems to be saying it wants the files read into the other classes...but I'm quite sure I only want one payroll at once, so it must just be worded oddly!

              Seeing as I have to read in data for both demonstrators and employees, you are saying that I should do that in two different arrays with two different methods in the payroll class?

              I then make a method in payroll to create an array of person to add these to, through other methods.

              Ok I think im understanding now. Hopefully everything goes to plan, if not I'll be back in an hour or two :).

              By the way, in all the other programs I have made, the objects have been constructed directly from the main method in the test class (ie Person bob = new person(paramete rs)), if I am making the objects through methods, I presume I call them from the main method. I'm not entirely sure how to do this... On thinking about it I guess I'm supposed to do Payroll test = new Payroll, and then call the methods through that instance. Though I'm not entirely sure what the constructor should be, and if it somehow has an array in it....another push in the right direction would be extremely well received. (Edit- just realised I can make new instances without a constructor in the class, and call all the methods through that)

              Thanks so much for your help so far, I'm having quite a bit of trouble with the way my course is being taught in regards to java...

              Comment

              • jkmyoung
                Recognized Expert Top Contributor
                • Mar 2006
                • 2057

                #8
                It looks like the spec wants you to use a general Person array in your payroll class. How do you know how many employees you have? It looks like nothing needs to be static. Assuming public static Person[] people is initialized in your constructor, you can have:
                Code:
                public void readinfo() throws FileNotFoundException 
                {      
                    Scanner inFile = new Scanner(new FileReader("EmployeeData.txt")); // read in employees.
                    int i = 0;
                    while(inFile.hasNext()) {
                         people[i]= new Employee(inFile.next(), inFile.next(), inFile.next(), inFile.next(), inFile.nextInt(), inFile.nextDouble()); 
                         i++;
                    } 
                    inFile.close();
                
                    //next file
                    inFile = new Scanner(new FileReader("DemonstratorData.txt")); // read demonstrators
                    while(inFile.hasNext()) {
                         people[i]= new Demonstrator( ..... arguments here); 
                         i++;
                    } 
                    inFile.close();
                }
                Notice how you keep using i. Once you fill up the array with employees, you can fill in the rest of it with the demonstrators.
                Note: You may need to resize your array. Ideally, you would use a Vector, but I don't know if you have that as an option.

                Comment

                • Jimmysevens
                  New Member
                  • Apr 2010
                  • 5

                  #9
                  An absolute Godsend you are!

                  Indeed i've been looking at arraylists (googling for changing the size of arrays actually brought me to this site haha), but I dont seem to quite get it/dont think were expected to use them. I might just pick a large array and mention it in the documentation. By the way, I get to pick the format for my textfiles, and therefore tried to use that to establish the size of the array, but I can only manage to do that when the array is in the method, and keep hitting dead ends. I'm therefore guessing this is impossible in java and ive been going round in circles trying to do the impossible every so often.

                  thanks so much yet again, really set me straight!

                  Comment

                  Working...