gpt4 book ai didi

java - 尝试调用方法时出错

转载 作者:行者123 更新时间:2023-12-01 20:03:51 25 4
gpt4 key购买 nike

我一直在网上查找,但我仍然不确定如何在我的子类中调用方法。我试图在 Executive 中调用 pay() 方法,当我在 if 语句中输入以下代码时,我不断收到错误。

staff[3].awardBonus(bonus);

我用这个方法总是出错。我不知道如何调用该方法...感谢您的帮助!`import java.util.Scanner;

    import java.util.Scanner;
public class Tester
{
public static void main (String args[])
{
Scanner scan = new Scanner(System.in);
StaffMember[] staff = new StaffMember[4];
String internName = "Susan 2";
String empName = "Tyler O.";
String hrName = "Becky R.";
String execName = "Daniel H.";
String address = "Brighton";
String phone = "420 - 0000";
String SSN = "12345789";
double rate = 1000;

staff [0] = new Intern(internName, address, phone);
staff [1] = new Employee(empName, address, phone, SSN, rate);
staff [2] = new HourlyEmployee(hrName, address, phone, SSN, rate);
staff [3] = new Executive(execName, address, phone, SSN, rate);


for (StaffMember staffPrint : staff)
{
System.out.println (staffPrint.toString() + "\n");
}

System.out.println("If you would like to give an executive a bonus, press 1. \nIf you would like to increase the hours of an hourly employee, press 2.");
int input = scan.nextInt();
if(input == 1)
{
double bonus = 0;
System.out.println("Enter the bonus for your employee: ");
bonus = scan.nextDouble();

}
}

这是 Executive 类、Employee 类和 StaffMember 类

public class Executive extends Employee
{
public Executive(String name, String address, String phone, String SSN, double rate)
{
super(name, address, phone, SSN, rate);
}

public double pay()
{
double money = super.pay();
return money;
}

public String toString()
{
String employee = super.toString();
return employee;
}

public void awardBonus(double execBonus)
{
rate += execBonus;
}
}

员工

    public class Employee extends StaffMember
{
String SSN;
double rate;

public Employee(String name, String address, String phone, String SSN, double rate)
{
super(name, address, phone);
this.SSN = SSN;
this.rate = rate;
}

public double pay()
{
return rate;
}

public String toString()
{
String employee = "";
employee = ("Name: " + name + "\nAddress: " + address + "\nPhone Number: " + phone + "\nSocial Security Number: " + SSN + "\nPay: " + pay());
return employee;
}
}

工作人员

public abstract class StaffMember
{
String name;
String address;
String phone;

public StaffMember(String name, String address, String phone)
{
this.name = name;
this.address = address;
this.phone = phone;
}

public String toString()
{
String employee = "";
employee = ("Name: " + name + "\nAddress: " + address + "\nPhone Number: " + phone);
return employee;
}

public abstract double pay();
}

最佳答案

staff 是一个 StaffMember 数组。当您引用其中的任何项目时(正如您执行 staff[3] 那样),您将获得一个 StaffMember

StaffMember 没有方法 awardBonus()

关于java - 尝试调用方法时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47690096/

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