0
public static void main(String[] args){

            Employee[] empList = new Employee[2];

        for(int i=0; i < empList.length; i++){
            String empType = JOptionPane.showInputDialog("Enter S for a salaried employee or H for an hourly employee.");
            if (empType.charAt(0) == 's' || empType.charAt(0) == 'S'){
                empList[i] = new Salaried();
                collectEmpInfo(empList[i]);
                displayEmpInfo(empList[i]);
                System.out.println("Number of Employees: " + Salaried.getNumEmployees());
            }
            else if (empType.charAt(0) == 'h' || empType.charAt(0) == 'H'){
                empList[i] = new Hourly();
                collectEmpInfo(empList[i]);
                displayEmpInfo(empList[i]);
                System.out.println("Number of Employees: " + Hourly.getNumEmployees());
            }
            else{
                JOptionPane.showMessageDialog(null, "Invalid Employee Type");
                //reset i for this iteration if input is invalid
                i--;
            }
        }

    }


import java.text.NumberFormat;
public abstract class Employee {

protected String firstName;
protected String lastName;
protected char gender;
protected int dependents;
protected double annualSalary;
protected static int numEmployees = 0;
public Benefit benefit;

public Employee(){
    firstName = "not given";
    lastName = "not given";
    gender = 'U';
    dependents = 0;
    annualSalary = 20000;
    benefit = new Benefit();

}

public Employee(String first, String last, char gen, int dep, double salary, Benefit ben){
    firstName = first;
    lastName = last;
    gender = gen;
    dependents = dep;
    annualSalary = salary;  
    numEmployees += 1;
    benefit = ben;
}



public String toString(){
    NumberFormat nf = NumberFormat.getCurrencyInstance();
    return "First Name:" + firstName + 
            "\nLast Name: " + lastName +
            "\nGender: " + gender +
            "\nDependents: " + dependents +
            "\nAnnual Salary: " + nf.format(annualSalary) +
            "\nEmployee weekly pay: " + nf.format(calculatePay()) +
            benefit.toString();


}

public String getFirstName(){
    return firstName;
}

public void setFirstName(String first){
    firstName = first;
}

public String getLastName(){
    return lastName;
}

public void setLastName(String last){
    lastName = last;
}

public char getGender(){
    return gender;
}

public void setGender(char gen){
    gender = gen;
}

public int getDependents(){
    return dependents;
}

public void setDependents(int dep){
    dependents = dep;
}

public double getAnnualSalary(){
    return annualSalary;
}

public void setAnnualSalary(double salary){
    annualSalary = salary;
}

public static int getNumEmployees(){
    return numEmployees;
}

public void setDependents(String dep){
    dependents = Integer.parseInt(dep);
}

public void setAnnualSalary(String sal){
    annualSalary = Double.parseDouble(sal);
}
public abstract double calculatePay();
}

public class Benefit {

private String healthInsurance;
private double lifeInsurance;
private int vacation;

public Benefit(){
    healthInsurance = "Full";
    lifeInsurance = 1000;
    vacation = 5;
}

public Benefit(String health, double life, int vacation){
    healthInsurance = health;
    lifeInsurance = life;
    this.vacation = vacation;
}

public String toString(){
    return "\nHealth Insurance: " + healthInsurance +       
           "\nLife Insurance: " + lifeInsurance + 
           "\nVacation: " + vacation;
}

public String getHealthInsurance(){
    return healthInsurance;
}

public void setHealthInsurance(String hins){
    healthInsurance = hins;
}

public double getLifeInsurance(){
    return lifeInsurance;
}

public void setLifeInsurance(double lifeins){
    lifeInsurance = lifeins;
}

public int getVacation(){
    return vacation;
}

public void setVacation(int vaca){
    vacation = vaca;
}
}

import java.text.NumberFormat;


public class Salaried extends Employee{

private final static int MIN_MANAGEMENT_LEVEL = 0;
private final static int MAX_MANAGEMENT_LEVEL = 3;
private final static double BONUS_PERCENT = 0.10;
private int managementLevel;

public Salaried(){
    firstName = "not given";
    lastName = "not given";
    gender = 'U';
    dependents = 0;
    annualSalary = 20000;
    benefit = new Benefit();
    managementLevel = 0;
}

public Salaried(int managementLevel){
    firstName = "not given";
    lastName = "not given";
    gender = 'U';
    dependents = 0;
    annualSalary = 20000;
    benefit = new Benefit();
    numEmployees +=1;
    this.managementLevel = (managementLevel >= MIN_MANAGEMENT_LEVEL && managementLevel <= MAX_MANAGEMENT_LEVEL)? managementLevel : 0;
}

public Salaried(String first, String last, char gen, int dep, double salary, Benefit bene, int managementLevel){
    firstName = first;
    lastName = last;
    gender = gen;
    dependents = dep;
    annualSalary = salary;  
    numEmployees += 1;
    benefit = bene;
    this.managementLevel = (managementLevel >= MIN_MANAGEMENT_LEVEL && managementLevel <= MAX_MANAGEMENT_LEVEL)? managementLevel : 0;
}

public double calculatePay(){
    double bonusPercentage = managementLevel * BONUS_PERCENT;
    double weeklyBonus = bonusPercentage * annualSalary;
    double weeklyPay = annualSalary/52 + weeklyBonus/52; 
    return weeklyPay;
}

public String toString(){
    NumberFormat nf = NumberFormat.getCurrencyInstance();
    return "First Name:" + firstName + 
            "\nLast Name: " + lastName +
            "\nGender: " + gender +
            "\nDependents: " + dependents +
            "\nAnnual Salary: " + nf.format(annualSalary) +
            "\nEmployee weekly pay: " + nf.format(calculatePay()) +
            benefit.toString() +
           "\nManagement Level: " + managementLevel;
}

public void setManagementLevel(int manLevel){
    managementLevel = (manLevel >= MIN_MANAGEMENT_LEVEL && manLevel <= MAX_MANAGEMENT_LEVEL)? manLevel : 0;
}

public int getManagementLevel(){
    return managementLevel;
}

}

import java.text.NumberFormat;


public class Hourly extends Employee{
private static final double MIN_WAGE = 10;
private static final double MAX_WAGE = 75;
private static final double MIN_HOURS = 0;
private static final double MAX_HOURS = 50;

private double wage;
private double hours;
private String category;

public Hourly(){
    wage = 0;
    hours = 0;
    category = "";
    firstName = "not given";
    lastName = "not given";
    gender = 'U';
    dependents = 0;
    annualSalary = 20000;
    numEmployees +=1;
    benefit = new Benefit();
}

public Hourly(double wage, double hours, String category){
    this.wage = (wage >= MIN_WAGE && wage <= MAX_WAGE)? wage : 10;
    this.hours = (hours >= MIN_HOURS && hours <= MAX_HOURS)? hours : 0;
    this.category = (category.equalsIgnoreCase("temporary") || category.equalsIgnoreCase("full time") || category.equalsIgnoreCase("part time"))? 
            category: "Invalid category";
    firstName = "not given";
    lastName = "not given";
    gender = 'U';
    dependents = 0;
    annualSalary = 20000;
    benefit = new Benefit();
}

public Hourly(String first, String last, char gen, int dep, Benefit bene, double wage, double hours, String category){
    this.wage = (wage >= MIN_WAGE && wage <= MAX_WAGE)? wage : 10;
    this.hours = (hours >= MIN_HOURS && hours <= MAX_HOURS)? hours : 0;
    this.category = (category.equalsIgnoreCase("temporary") || category.equalsIgnoreCase("full time") || category.equalsIgnoreCase("part time"))? 
            category: "Invalid category";
    double salary = wage * hours * 52;
    firstName = first;
    lastName = last;
    gender = gen;
    dependents = dep;
    annualSalary = salary;  
    numEmployees += 1;
    benefit = bene;
}

public String toString(){
    NumberFormat nf = NumberFormat.getCurrencyInstance();
    return "First Name:" + firstName + 
            "\nLast Name: " + lastName +
            "\nGender: " + gender +
            "\nDependents: " + dependents +
            "\nAnnual Salary: " + nf.format(annualSalary) +
            "\nEmployee weekly pay: " + nf.format(calculatePay()) +
            benefit.toString() +
           "\nCategory: " + category;
}

public double getWage() {
    return wage;
}

public void setWage(double wage) {
    this.wage = (wage >= MIN_WAGE && wage <= MAX_WAGE)? wage : 10;
    annualSalary = wage * hours *52;
}

public double getHours() {
    return hours;
}

public void setHours(double hours) {
    this.hours = (hours >= MIN_HOURS && hours <= MAX_HOURS)? hours : 0;
    annualSalary = wage * hours * 52;
}

public String getCategory() {
    return category;
}

public void setCategory(String category) {
    this.category = (category.equalsIgnoreCase("temporary") || category.equalsIgnoreCase("full time") || category.equalsIgnoreCase("part time"))? 
            category: "Invalid category";
}

public double calculatePay(){
    return wage * hours;
}
}

Employee is an abstract class containing the static int numEmployees. Salaried and Hourly are child classes of Employee. The constructors in both Salaried and Hourly increment numEmployees +=1, so why is it that when I call Salaried/Hourly.getNumEmployees() it returns 0?

Josh Eblin
  • 95
  • 1
  • 9
  • 2
    Please post those classes. – Sotirios Delimanolis Oct 10 '13 at 20:10
  • 1
    How can we guess at what's going wrong with your code if you post only irrelevant code? – nhgrif Oct 10 '13 at 20:15
  • 2
    My guess is that the subclasses have their own static variable that shadows super's – Bohemian Oct 10 '13 at 20:16
  • "Employee is an abstract class containing the static int numEmployees": KILL ME PLEASE! – Renato Oct 10 '13 at 20:31
  • 1
    Classes posted. @Renato instead of complaining about the code, perhaps explain why the code is wrong. – Josh Eblin Oct 10 '13 at 20:41
  • 1
    In addition to the answer posted to this question, you should not have `numEmployees` in the `Employee` class. An employee is a person, but number of employees is not an attribute of the employee. It sounds more like it should be part of a company, and when you add an employee to a company it increments the number of employees. – Jeff Storey Oct 10 '13 at 20:52

1 Answers1

2

The constructors with no parameters (the ones you call in main) are not incrementing the counter. Edit: well, at least not the one in Salaried...

Also, the counter is probably not going to work as you intended, since there's just one static counter for all subclasses.

Static fields in Java are not a good way to learn inheritance. They behave mostly like global variables. If you want to learn inheritance and polymorphism, you should focus on non-static methods. If needed, you can create a "Company" class, as suggested in the comments.

marcus
  • 5,041
  • 3
  • 30
  • 36
  • Unfortunately this program is for an OOP class focusing in Java. Part of the requirements are to use the classes defined above. Also, thank you for noticing that the default constructor in Salaried didn't increment numEmployees. I added that line to the default constructor and the program worked fine. I'm not sure I understand why a static method/field is not a good way to learn inheritance though. It seems to me that it doesn't make a difference. Anyhow, you did give me the solution to my problem, so thank you. – Josh Eblin Oct 11 '13 at 00:37
  • Hi Josh. I did not realize you're just learning programming, sorry for my comment. Static variables are usually very bad practice in Java. [See this](http://stackoverflow.com/questions/7026507/why-are-static-variables-considered-evil). As a general thing, completely avoid any static state at all! If you need to keep the number of employees somewhere, perhaps you should have class whose main purpose is to do just that. The Company class people are telling you about, for example. But why not just query the database (you probably will have one in any real app) for the number of employees? – Renato Oct 11 '13 at 08:22
  • In that case, you are free from the burden of having to keep track of the number of employees just in case someone asks it sometime. You must try to adhere to the "Single responsibility principle" when designing your classes. This will make your code a lot better. Good luck in your studies. – Renato Oct 11 '13 at 08:23