我有一个子类需要继承一个方法和一个变量,并且我希望能够创建该子类的多个实例。但是,我无法改变health
来自类 Glob 的值。
这是我的代码:
public class Monster
{
int health;
public int getHealth()
{
return health;
}
}
class Glob extends Monster
{
health = 6; // <- Error
}
最佳答案
你不能只是像这样隐藏父类(super class)的变量。你可以在构造函数中做到这一点 -
class Glob extends Monster
{
public Glob() {
health = 6;
}
}
关于java - 如何从父类继承变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28911493/