我有一个名为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;
}
最佳答案
你不能。强制转换不会改变对象的任何内容,它只是告诉编译器可以将对象解释为一个类,该类位于类层次结构的最上层,而不能向下。一旦实例化一个对象,就是这样-该对象无疑是您实例化的类的成员,并且是不可撤销的成员。它是一个BasketballPlayer
,永远不会是ProBasketballPlayer
。如果您想要专业版,请实例化一个-您可以将Pro用作普通的篮球运动员,反之则不行。
举个例子:
class Foo
{
int a;
}
class Bar extends Foo
{
int b;
}
Foo obj = new Foo();
obj.a = 0; // our obj has an "a" field because it is a Foo.
obj.b = 0; // but no "b" field, because it is not a Bar.
// It therefore makes no sense to do this:
((Bar)obj).b = 0; // because that's the same as trying to do "obj.b"
// in either case, "obj" is not a "Bar", and cannot have a "b" field. "obj" will always be a "Foo", never a "Bar".
//
// If however we make a Bar:
Bar obj2 = new Bar();
// we can access both fields, since Bar has both of them
obj2.a = 0;
obj2.b = 0;
// and, since Bar is a SUPERSET of Foo (all Bar are Foo, not all Foo are Bar),
// we can even use obj2 as a Foo, and pass it to methods which accept a Foo.