简体   繁体   English

创建从一个类扩展到数组列表的对象

[英]Creating Objects that Extend from one Class to put in array list

I'm trying to write a payroll program that simply receives input, does some calculations and displays the output for EACH employee. 我正在尝试编写一个工资单程序,该程序仅接收输入,进行一些计算并显示每个员工的输出。

I have two types of employees, hourly and salary. 我有两种类型的员工,小时工和薪水。 I created a class for each type that extends to an abstract employee class: 我为每种类型都创建了一个类,该类扩展到抽象的雇员类:

public abstract class Employee{
  private String name;
  private String type;
  private  int hours;
  private double rate;
}


public class SalaryEmployee extends Employee{

  public SalaryEmployee(String type, String name, int hours, double rate){
   this.type = type;
    this.name = name;
    this.hours = hours;
    this.rate = rate;
  }

  public void print(){

  }
}

In my main method, when I try to create my objects using the code below: 在我的主要方法中,当我尝试使用以下代码创建对象时:

  Employee employee;
  if(type.equals("hourly"))
  {
    employee = new HourlyEmployee(type, name, hours, rate);
  }
  else
  {
    employee = new SalaryEmployee(type, name, hours, rate);
  }

I get the following error when I try to compile: 尝试编译时出现以下错误:

Lab3.java:53: not a statement
        SalaryEmployee employee = new SalaryEmployee(type, name, hours, rate);
         ^
Lab3.java:53: ';' expected
        SalaryEmployee employee = new SalaryEmployee(type, name, hours, rate);
                      ^
2 errors

Any idea what is happening here? 知道这里发生了什么吗? I've looked around for messing semi colons or braces, but haven't found anything yet. 我到处寻找混乱的半冒号或大括号,但尚未找到任何东西。

Thanks for looking. 感谢您的光临。

It is illegal to declare a variable in an if that does not use braces. 在不使用花括号的情况下声明变量是违法的。 It looks like what you meant to write is something like this: 看起来您打算写的是这样的:

Employee employee;
if(type.equals("hourly"))
  employee = new HourlyEmployee(type, name, hours, rate);
else
  employee = new SalaryEmployee(type, name, hours, rate);

Most coding conventions support always using braces after an if or else. 大多数编码约定都支持始终在if或else之后使用花括号。

The only error I can see is that your SalaryEmployee class cannot access the base class variables because they are private . 我看到的唯一错误是您的SalaryEmployee类无法访问基类变量,因为它们是private变量。 You should make them protected . 您应该protected它们。

Although, the error you are getting would be different.. If you are still getting the error after changing, your error is probably lying elsewhere. 虽然,您得到的错误会有所不同。如果更改后仍然出现错误,则您的错误可能在其他地方。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM