我对扩展课程有些困惑。我认为解释我想做的最好的方法是使用一些骨架代码:
abstract class Player
{
public int solve()
{ // One method of solving problem
}
}
class otherPlayer extends Player
{
public char solve(int num)
{ //Different method of solving same problem
}
}
// I suspect this is a wrong way to create Player
Player first = new otherPlayer;
// Because this gives me an error...
first.solve(5)'
// And this uses the super class's method of solving problem
first.solve();
// I don't want to do this though...
otherPlayer first = new otherPlayer;
// Because I actually define the Players in a method
// that returns a type Player():
private Player genPlayer()
{ // Take input from keyboard
Player newPlayer;
if (specific set of answers)
newPlayer = new otherPlayer();
else newPlayer = new Player();
return newPlayer;
}
我对扩展类的理解是有限的。如果我说“TypeA var = new TypeB”,而 TypeB 扩展了 TypeA,那么 var 似乎只能访问 TypeA 类中的方法。它是做什么的,那么说它是一个新的TypeB?为什么这甚至是实例化变量的合法方式?你会如何建议我重组这个程序以便让它工作(我宁愿保留这个方法,这样我每次创建播放器时都不必弄得一团糟)?
我真的只是想知道如何创建一个扩展类,就好像我是一个知道自己在做什么的人一样。