gpt4 book ai didi

java - 如何访问扩展类中的方法?

转载 作者:行者123 更新时间:2023-12-01 17:42:01 26 4
gpt4 key购买 nike

我有以下内容:

main.java

public class main {
public static void main(String[] args){
Player startingPitcher = new Player("Doug", "Mellon",
"Pitcher", 29);

startingPitcher.setThrowingArm("right");
}
}

Player.java

class Player
{
private String firstName, lastName, position;
private int age;

public Player(String firstName, String lastName, String position, int age)
{
this.firstName = firstName;
this.lastName = lastName;
this.position = position;
this.age = age;
}

private String getFirstName(){
return this.firstName;
}

private void setFirstName(String newFirstName){
this.firstName = newFirstName;
}

private String getLastName(){
return this.lastName;
}

private void setLastName(String newLastName){
this.lastName = newLastName;
}

private String getPosition(){
return this.position;
}

private void setPosition(String newPosition){
this.position = newPosition;
}

private int getAge(){
return this.age;
}

private void setAge(int newAge){
this.age = newAge;
}
}

投手.java

public class Pitcher extends Player{

public String throwingArm;
public int fastballMPH;


public Pitcher(String firstName, String lastName, String position, int age,
String throwingArm, int fastballMPH) {
super(firstName, lastName, position, age);
this.throwingArm = throwingArm;
this.fastballMPH = fastballMPH;
}

public String getThrowingArm(){
return this.throwingArm;
}

public void setThrowingArm(String newThrowingArm){
this.throwingArm = newThrowingArm;
}

private int getFastballMPH(){
return this.fastballMPH;
}

private void setFastballMPH(int newFastballMPH){
this.fastballMPH = newFastballMPH;
}
}

我的主要抛出以下错误:

Error:(6, 24) java: cannot find symbol symbol: method setThrowingArm(java.lang.String) location: variable startingPitcher of type Player

我理解这个错误 - 我认为 - 但我认为如果您使用继承,您可以访问这些方法。

如何为主对象中的 Player 对象设置 throw 臂?

很抱歉,如果这个问题措辞不好。如果我可以添加任何内容来澄清我的问题,请随时提问。

非常感谢大家抽出宝贵的时间。

最佳答案

main 类的 main() 方法中的

变量 startingPitcherPlayer 的实例,而不是Pitcher 的实例,因此它没有 setThrowingArm() 方法。

您需要创建一个 Pitcher 实例,即

Pitcher startingPitcher = new Pitcher("Doug", "Mellon", "pitcher", 29, "right", 90);

请注意,这是错误消息告诉您的内容,即变量 startingPitcherPlayer 的实例(并且不是实例) 投手)。

关于java - 如何访问扩展类中的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59906706/

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