473,513 Members | 2,620 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Multiple classes, arrays, static, non-static issues

5 New Member
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 getEmployeeArray() 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.getEmployeeArray().

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!
Apr 22 '10 #1
8 2763
jkmyoung
2,057 Recognized Expert Top Contributor
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.
Apr 22 '10 #2
Jimmysevens
5 New Member
Here is the code for the parts of the person class I think are relevant, (version of readinfo() that is non-static).
Expand|Select|Wrap|Line Numbers
  1. import java.util.*;
  2. import java.io.*;
  3.  
  4. public class Employee extends Person 
  5. {           
  6.     private double salary;
  7.     public Person[] employ = new Person[15];
  8.  
  9.     public Employee (String f, String l, String d, String n, int t, double s)
  10.     {
  11.         super(f,l,d,n,t);
  12.         salary = s;
  13.     }        
  14.  
  15.     public void readinfo() throws FileNotFoundException
  16.     {     
  17.         Scanner inFile = new Scanner(new FileReader("EmployeeData.txt"));
  18.          for (int i=0; i<inFile.nextInt(); i++)
  19.             {
  20.                 employ[i]= new Employee(inFile.next(), inFile.next(), inFile.next(), inFile.next(), inFile.nextInt(), inFile.nextDouble());
  21.               }
  22.         }   
  23.  
  24.         public Person[] getarray()
  25.         {
  26.          return employ  ;
  27.         }
  28.  
  29.     public void showDetails()
  30.     {
  31.         super.showDetails();
  32.         System.out.println ("Salary = " + salary + "\n");
  33.     }
  34.  
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.

Expand|Select|Wrap|Line Numbers
  1. public class Payroll()
  2. public static void showempDem() throws FileNotFoundException
  3. {
  4.     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.//
  5.     System.out.println("----------EMPLOYEES:----------");
  6.  
  7.     for (int i = 0; i<employees.length; i++)
  8.     {
  9.         System.out.println(i);
  10.         employees[i].showDetails()
  11.     }
  12.  }
  13.  
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.
Apr 22 '10 #3
jkmyoung
2,057 Recognized Expert Top Contributor
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.
Apr 22 '10 #4
Jimmysevens
5 New Member
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:
Expand|Select|Wrap|Line Numbers
  1. public class Employee extends Person 
  2. {           
  3.     private double salary;
  4.  
  5.     public Employee (String f, String l, String d, String n, int t, double s)
  6.     {
  7.         super(f,l,d,n,t);
  8.         salary = s;
  9.     }        
  10.  
  11.     public static void readinfo() throws FileNotFoundException
  12.     {     
  13.         Scanner inFile = new Scanner(new FileReader("EmployeeData.txt"));
  14.         public static Person[] employ = new Employee[inFile.nextInt];
  15.         for (int i=0; i<employ.length; i++)
  16.        {
  17.             employ[i]= new Employee(inFile.next(), inFile.next(), inFile.next(), inFile.next(), inFile.nextInt(), inFile.nextDouble());
  18.        }
  19.  
  20.        return employ;
  21.     }   
  22.  
  23.     public void showDetails()
  24.     {
  25.         super.showDetails();
  26.         System.out.println ("Salary = " + salary + "\n");
  27.     }
  28.  
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(edited 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.txt” and demonstrator information from a file “DemonstratorData.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 runPayrollMonthly 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.!
Apr 22 '10 #5
jkmyoung
2,057 Recognized Expert Top Contributor
"Payroll class stores an array of Person"
Not sure how much of it is due to incorrect cutting and pasting, but it should be:
Expand|Select|Wrap|Line Numbers
  1. class Payroll {
  2.   public Person[] employ = new Person[15]; 
  3.  
  4.   public static void readinfo() throws FileNotFoundException 
  5.     {   
  6.   ... 
  7.   }
  8.  
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.
Apr 22 '10 #6
Jimmysevens
5 New Member
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(parameters)), 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...
Apr 22 '10 #7
jkmyoung
2,057 Recognized Expert Top Contributor
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:
Expand|Select|Wrap|Line Numbers
  1. public void readinfo() throws FileNotFoundException 
  2. {      
  3.     Scanner inFile = new Scanner(new FileReader("EmployeeData.txt")); // read in employees.
  4.     int i = 0;
  5.     while(inFile.hasNext()) {
  6.          people[i]= new Employee(inFile.next(), inFile.next(), inFile.next(), inFile.next(), inFile.nextInt(), inFile.nextDouble()); 
  7.          i++;
  8.     } 
  9.     inFile.close();
  10.  
  11.     //next file
  12.     inFile = new Scanner(new FileReader("DemonstratorData.txt")); // read demonstrators
  13.     while(inFile.hasNext()) {
  14.          people[i]= new Demonstrator( ..... arguments here); 
  15.          i++;
  16.     } 
  17.     inFile.close();
  18. }
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.
Apr 22 '10 #8
Jimmysevens
5 New Member
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!
Apr 23 '10 #9

Sign in to post your reply or Sign up for a free account.

Similar topics

13
12018
by: jing_li | last post by:
Hi, you all, I am a newbee for php and I need your help. One of my coworker and I are both developing a webpage for our project using php. We have a copy of the same files in different location on the server (in our own accounts on the same machine). When I am testing both versions of our program using the same browser (IE on Windows or...
17
43871
by: Roland Hall | last post by:
Is there a way to return multiple values from a function without using an array? Would a dictionary object work better? -- Roland Hall /* This information is distributed in the hope that it will be useful, but without any warranty; without even the implied warranty of merchantability or fitness for a particular purpose. */ Technet Script...
3
1654
by: Emmanuel Thomé | last post by:
This is a comment aside the empty class behavior FAQ. I understand there are a fair number of reasons which make empty classes have non-zero size (except as base classes). If ``class foo'' were of size 0, then: - an object of type foo may lie at the same address as another. - arrays of foo objects would have size 0, and pointer arithmetic...
5
2219
by: vj | last post by:
Hi all, I am using C++Builder-5. I want to run multiple cpp files at the same time. If I use the C++Builder for running a cpp file (i.e., I just double click the cpp file, it then opens in the C++Builder, where I have the option to 'Run' it), I can't run multiple files, since the Run option is grayed out if one cpp file is already running....
4
2109
by: Chris F Clark | last post by:
Please excuse the length of this post, I am unfortunately long-winded, and don't know how to make my postings more brief. I have a C++ class library (and application generator, called Yacc++(r) and the Language Objects Library) that I have converted over to C#. It works okay. However, in the C# version, one has to build the class library...
4
4672
by: Matt Kruse | last post by:
While developing an internal IE6-only webapp, a discussion started about the 'best' way to apply classes to data tables across multiple pages. The two arguments were: 1. Apply a single class to each table. That class (possibly in combination with other classes on child elements) controls every part of the table - layout, colors, fonts, etc....
3
2536
by: Jess | last post by:
Hello, I've been reading Effective C++ about multiple inheritance, but I still have a few questions. Can someone give me some help please? First, it is said that if virtual inheritance is used, then "the responsibility for initializing a virtual base is borne by the most derived class in the hierarchy". What does it mean? Initializing...
47
3953
by: Larry Smith | last post by:
I just read a blurb in MSDN under the C++ "ref" keyword which states that: "Under the CLR object model, only public single inheritance is supported". Does this mean that no .NET class can ever support multiple inheritance. In C++ for instance I noticed that the compiler flags an error if you use the "ref" keyword on a class with multiple...
13
3750
by: Eric IsWhoIAm | last post by:
I have four tables created so far: Courses, Instructors, Courses and Instructors (which shows the Course and Instructor Name fields, but holds their IDs since those are the keys), and Students. Now, I wish to create a Classrooms (or something similar) table which will allow me to pick the Course from Courses and Instructors, and hold multiple...
6
2552
by: ManicQin | last post by:
Let's ignore for a minute design decisions , readability and any other of those parameters , In the most raw form of c++ (purely efficiency if you want) what is better, bloating up a classes or breaking them up to small classes? (and again pure efficiency of the compiler) Thanks
0
7178
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
7397
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
1
7125
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
7543
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
3252
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
0
3239
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
1612
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
813
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
470
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.