假设您有代表枪的类和代表子弹的类。 扩展枪的类可以拥有自己特定的扩展子弹类,并且枪父类(super class)可以处理它们的数组。
在这个例子中,我有两个 Gun 扩展类,每个类都想使用不同类型的子弹扩展类,但让 super 处理添加到数组中(以避免一堆代码重复)
伪:
class Gun{
ArrayList<Bullet> bullets;
Gun(x,y,z){
}
void shoot(){
//add bullet to bullets array
}
}
class CustomGun extends Gun{
CustomGun(x,y,z){
//do stuff
}
//want super.shoot() to add CustomBullet to bullets array
}
class CustomGunTwo extends Gun{
CustomGunTwo(x,y,z){
//do stuff
}
//want super.shoot() to add CustomBulletTwo to bullets array
}
class Bullet{
Bullet(x,y,z){
//do stuff
}
}
class CustomBullet extends Bullet{
CustomBullet(x,y,z){
super(x, y, z)
}
}
class CustomBulletTwo extends Bullet{
CustomBullet(x,y,z){
super(x, y, z)
}
}
最佳答案
您无法更改父类(super class)中方法的行为。但您可以覆盖它,并实现不同的行为(在子类中)。为了实现这一点,需要适本地实现父类(super class)。
在您的示例中,您已为 bullets
留下了包私有(private)访问权限,因此 CustomGunTwo
中的方法可以将自定义项目符号插入列表中。如果bullets
有私有(private),那是不可能的。
但请考虑一下:
public class Gun {
private ArrayList<Bullet> bullets;
public void shoot(){
load(new Bullet());
}
protected void load(Bullet bullet) {
bullets.add(bullet);
}
}
public class CustomGun extends Gun {
@Override
public void shoot() {
load(new CustomBullet());
}
}
这里我们设计了Gun
类以允许子类修改加载行为。
关于java - 扩展类可以告诉它的 super 函数使用某个类吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41978586/