【发布时间】:2016-04-27 03:41:43
【问题描述】:
我有一个叫做 BasketBallPlayer 的超类
我有一个名为 ProBasketBallPlayer 的子类
如果我创建一个对象
BasketBallPlayer bp1;
bp1=new BasketBallPlayer("Tim Duncan", "Center", "Spurs", 83, 220, 4, 5, 8);
public class BasketBallPlayer {
protected String name;
protected String position;
protected String team;
protected int height;
protected int weight;
protected int agility;
protected int speed;
protected int ballHandling;
public BasketBallPlayer() {
this.name = "unknown";
this.position = "unknown";
this.team = "unknown";
this.height = 0;
this.weight = 0;
this.agility = 0;
this.speed = 0;
this.ballHandling = 0;
}
public BasketBallPlayer( String name, String position, String team)
{
this.name = name;
this.position = position;
this.team = team;
this.height = 0;
this.weight = 0;
this.agility = 0;
this.speed = 0;
this.ballHandling = 0;
}
public BasketBallPlayer (String name, String position, String team, int height, int weight,
int agility, int speed, int ballHandling)
{
this.name = name;
this.position = position;
this.team = team;
this.height = height;
this.weight = weight;
this.agility = agility;
this.speed = speed;
this.ballHandling = ballHandling;
}
如何在不出现 ClassCastException 的情况下将其类型转换为 ProBasketballPlayer
这是 ProBasketballPlayer 的构造函数
public class ProBasketballPlayer extends BasketBallPlayer {
protected int yearsInLeague;
protected String role;
public ProBasketballPlayer()
{
super();
yearsInLeague = 0;
role = "bench";
}
public ProBasketballPlayer( String name, String position, String team )
{
super(name, position, team);
this.name = name;
this.position = position;
this.team = team;
yearsInLeague = 0;
role = "bench";
}
public ProBasketballPlayer(String name, String position, String team, int height, int weight,
int agility, int speed, int ballHandling, int yearsInLeague, String role)
{
super(name, position, team, height, weight, agility, speed, ballHandling);
this.yearsInLeague = yearsInLeague;
this.role = role;
}
【问题讨论】:
-
您只能将子类转换为其超类,反之则不行。简单来说,法拉利是一种车,但车不是法拉利的一种。我可以创建一个 List
并将梅赛德斯、法拉利和福特汽车添加到列表中,考虑到这些子类中的每一个都有一个超类 Car。 -
你应该让你的蒂姆邓肯节食。在 83 厘米的高度体重 220 磅听起来并不健康。
-
@RolandIllig 有些东西告诉我它是英寸... XD
-
@4castle:感谢您的解释。 — 所以这个程序应该只由美国人来维护,而不是由欧洲人来维护。因为对他们来说,可能看起来身高(220 厘米)和体重(83 公斤)混在一起,导致球员身材高大但非常瘦。
标签: java class oop object inheritance