java - 如何通过继承抽象类的类从 main 调用抽象类的静态变量访问器?

标签 java inheritance abstract-class

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 是一个抽象类,包含 static int numEmployees。 Salaried 和 Hourly 是 Employee 的子类。 Salaried 和 Hourly 中的构造函数都递增 numEmployees +=1,那么为什么当我调用 Salaried/Hourly.getNumEmployees() 时它返回 0?

最佳答案

没有参数的构造函数(您在 main 中调用的构造函数)不会递增计数器。 编辑:好吧,至少不是薪水中的那个......

此外,计数器可能不会按您的预期工作,因为所有子类只有一个静态计数器。

Java 中的静态字段并不是学习继承的好方法。它们的行为大多类似于全局变量。如果你想学习继承和多态,你应该关注非静态方法。如果需要,您可以按照评论中的建议创建一个“Company”类。

关于java - 如何通过继承抽象类的类从 main 调用抽象类的静态变量访问器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19305248/

相关文章:

java - Android studio 中按钮不是正方形但宽度和高度相同?

c++从父类实例化 protected 成员

php - 在 PHP 中将属性值作为字符串文字访问

c# - 用具体类型覆盖抽象方法

java - Android中的循环线程启动

java - java虚拟方法调用有什么用?

java - 如何在 Spring 运行时向 bean 添加属性

java - 抽象类扩展了Java和Android的多种类型的 Activity

c++ - 具有不同数据类型的纯虚拟方法

Java-JPA : How can I create a table for each subclass but not for superclass?