gpt4 book ai didi

Java:是否有可能排除从父类(super class)中获取某些东西

转载 作者:搜寻专家 更新时间:2023-10-31 20:08:40 25 4
gpt4 key购买 nike

我正在处理一项处理类继承的作业,除了字符串格式方法外,一切都已完成并正常工作。该程序的输出应如下所示:

Base Salary Plus Commissioned Employee: Sue Smith with ssn: 222-22-2222
Gross Sales: $3000.00
Commission Rate: 0.05
with Base Salary:$300.00
Earnings: $450.00

但是它是这样打印的:

Base Salary Plus Commissioned Employee: Sue Smith with ssn: 222-22-2222
Gross Sales: $3000.00
Commission Rate: 0.05
Earnings: $450.00
with Base Salary:$300.00
Earnings: $450.00

问题是在输出中,“Earnings: $450.00”打印在“with Base Salary: $300.00”之前。 BasePlusCommissionEmployee 类继承自 CommissionEmployee 类。每个类都有自己的 toString 方法,BasePlusCommissionEmployee 确实调用了 super.toString(),我认为这是导致问题的原因。

我需要能够让类从 CommissionEmployee 继承,但直到最后才带来“ yield ”(如图所示)。

这是 CommissionEmployee 类中 toString 的代码:

    @Override
public String toString() {
return String.format("%s: %s%n%s: $%.2f \n%s: %.2f \n%s $%.2f",
"Commissioned Employee", super.toString(),
"Gross Sales", getGrossSales(),
"Commission Rate", getCommissionRate(),
"Earnings:", earnings());
}

这是 BasePlusCommissionEmployee 类(从 CommissionEmployee 扩展)中的 toString 代码:

    @Override
public String toString() {
return String.format("\n%s %s \n%s:$%,.2f \n%s $%.2f",
"Base Salary Plus", super.toString(),
"with Base Salary", getBaseSalary(),
"Earnings:",earnings());
}

这是在main中运行的测试代码:

CommissionEmployee employee1 = new CommissionEmployee("Fred", "Jones", "111-11-1111", 2000.0, .05);
BasePlusCommissionEmployee employee2 = new BasePlusCommissionEmployee("Sue", "Smith", "222-22-2222", 3000.0, .05, 300);
System.out.printf("%s%s%s%s%s", employee1, employee2, employee3, employee4, employee5);

非常感谢所有帮助!谢谢!

最佳答案

本书的第一章几乎解决了这个问题 Refactoring由 Martin Fowler 撰写,“分解和重新分配声明方法”部分。 toString()方法在基类中可以分解如下:

    @Override
public String toString() {
return getReportHeader()
+ getReportBase()
+ getReportSpecifics()
+ getReportFooter();
}

protected String getReportHeader() {
return String.format("%s: %s",
"Commissioned Employee", super.toString());
}

protected String getReportBase() {
return String.format("\n%s %s \n%s:$%,.2f",
"Gross Sales", getGrossSales(),
"Commission Rate", getCommissionRate());
}

protected String getReportSpecifics() {
return "";
}

protected String getReportFooter() {
return String.format("\n%s $%.2f", "Earnings:", earnings());
}

然后可以在子类中覆盖所需的部分:

    @Override
protected String getReportSpecifics() {
return String.format("\n%s %s \n%s:$%,.2f",
"Base Salary Plus", getBaseSalaryPlus(),
"with Base Salary", getBaseSalary());
}

不过,我建议您阅读整本书。它物有所值。

关于Java:是否有可能排除从父类(super class)中获取某些东西,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48548462/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com