gpt4 book ai didi

java - 如何在子类中使用相同的方法名调用父类(super class)的方法

转载 作者:行者123 更新时间:2023-12-01 07:32:22 25 4
gpt4 key购买 nike

我对重写父类(super class)中的方法感到有点困惑。谁能帮我解决这个加粗的问题吗?我不太确定如何在“篮球”的主方法中调用“say”方法。

一支篮球队有 12 名球员。每个球员都是 3 种类型之一 - 中锋、后卫、前锋。

一支球队有 4 名中锋、4 名前锋和 4 名后卫。

每个玩家都有唯一的名字和唯一的号码。

定义一个基类Player。 Player 类有一个名称成员、一个字符串和一个数字成员、一个整数。

从 Player 类派生出 Center 类、Guard 类和 Forward 类。

为基类和派生类定义适当的构造函数、访问器和修改器。

定义一个基类方法,Say。说显示玩家的姓名和号码

在派生类中重写基类 Say 方法。派生类的 Says 显示玩家的位置并调用基类 Say。基类 Say 和派生类 Says 一起显示玩家的姓名、号码和类型

public class Player
{
protected String firstName;
protected String lastName;
protected int num;

public Player(String first, String last, int jerseyNum)
{
firstName = first;
lastName = last;
num = jerseyNum;
}

public void setFirstName(String first)
{
firstName = first;

}

public String getFirstName()
{
return firstName;
}

public void setLastName(String last)
{
lastName = last;
}

public String getLastName()
{
return lastName;
}

public void setNum(int jerseyNum)
{
num = jerseyNum;
}

public int getNum()
{
return num;
}

public void say()
{
System.out.printf("The player's name is %s %s and his jersey number is %d.\n", firstName, lastName, num);

}
}

public class Center extends Player
{
private String center;

public Center(String first, String last, int num, String position)
{
super(first, last, num);
center = position;
}

public void setPosition(String position)
{
center = position;
}

public String getPosition()
{
return center;
}

@Override
public void say()
{
System.out.printf("This player plays the %s position", center);
}
}


public class Forward extends Player
{
private String forward;

public Forward(String first, String last, int num, String position)
{
super(first, last, num);
forward = position;
}

public void setPosition(String position)
{
forward = position;
}

public String getPosition()
{
return forward;
}

@Override
public void say()
{
System.out.printf("This player plays the %s position", forward);
}
}



public class Guard extends Player
{
private String guard;

public Guard(String first, String last, int num, String position)
{
super(first, last, num);
guard = position;
}

public void setPosition(String position)
{
guard = position;
}

public String getPosition()
{
return guard;
}

@Override
public void say()
{
System.out.printf("This player plays the %s position", guard);
}
}
public class basketball
{
public static void main(String[] Args)
{
//Player bballPlayer = new Player("Jon", "Jones", 25);
Center positionCenter = new Center("Jon", "Jones", 25, "Center");

positionCenter.say();
}
}

最佳答案

您可以使用 super. 调用父类(super class)方法,如下例所示:

@Override
public void say() {
super.say();
System.out.printf(" This player plays the %s position", guard);
}

关于java - 如何在子类中使用相同的方法名调用父类(super class)的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16312157/

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