我有两个java类:
class Employee{
private name;
private annualSalary;
public Employee(String name, double annualSalary){
}
}
和
class HourlyEmployee extends Employee{
public HourlyEmployee(String name, double annualSalary, double hourlySalary){
super(salary, annualSalary);
this.hourly = hourlySalary;
}
}
是否有一种方法可以从继承的类中摆脱annualSalary
的理解,那就是AnnualSalary = hourlySalary * 200?默认情况下,创建HourlyEmployee类时。 AnnualSalary的值将为空或设置为hourlySalary * 200。
答案 0 :(得分:2)
删除@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
@Column(name="firstname")
private String firstName;
@Column(name="lastname")
private String lastName;
private String password;
private String username;
@Column(name="accesstype")
private String accessType;
public User() {
super();
}
public User(String firstName, String lastName, String password,
String username, String accessType) {
super();
this.firstName = firstName;
this.lastName = lastName;
this.password = password;
this.username = username;
this.accessType = accessType;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getAccessType() {
return accessType;
}
public void setAccessType(String accessType) {
this.accessType = accessType;
}
}
并将annualSalary
传递给超类构造函数。
hourlySalary * 200
答案 1 :(得分:2)
您的班级结构错误,因为并非所有员工都获得年薪。摆脱annualSalary
中的Employee
并创建两个子类:具有小时薪的HourlyEmployee
和具有年薪的SalariedEmployee
。如果需要,请在getAnnualSalary
中引入抽象方法Employee
(并使Employee
抽象)并在两个子类中以不同的方式实现。
abstract class Employee {
private String name;
public Employee(String name) { ... }
public abstract double getAnnualSalary();
}
class SalariedEmployee extends Employee {
private double annualSalary;
public SalariedEmployee(String name, double annualSalary) {
super(name);
this.annualSalary = annualSalary;
}
@Override
public double getAnnualSalary() { return annualSalary; }
}
class HourlyEmployee extends Employee {
private double hourlySalary;
public HourlyEmployee(String name, double hourlySalary) {
super(name);
this.hourlySalary = hourlySalary;
}
@Override
public double getAnnualSalary() { return 200 * hourlySalary; }
}
您可能还想探索使用接口定义员工行为,而不是使用基类。
答案 2 :(得分:1)
需要省略父类属性是一种称为refused bequest的代码气味。如果小时工没有年薪,则代表小时工的类不应继承代表受薪雇员的类。
解决方案是根据情况将它们共有的部分提取到一个单独的类或几个不同的类中。在您当前的人为设计示例中,这两个类没有什么共同点,我认为使用继承开始毫无意义。