【问题标题】:How do I inherit a variable from a parent class? [duplicate]如何从父类继承变量? [复制]
【发布时间】:2015-03-07 04:47:40
【问题描述】:

我有一个需要继承方法和变量的子类,我希望能够创建子类的多个实例。但是,我无法更改 Glob 类中 health 的值。

这是我的代码:

public class Monster
{
int health;

    public int getHealth()
    {
        return health;
    }
}

class Glob extends Monster
{
    health = 6; //  <- Error
}

【问题讨论】:

  • 你还没有具体是什么问题。您发布的代码似乎有效,但您试图使其工作的代码在哪里?

标签: java variables inheritance parent-child subclass


【解决方案1】:

你不能像那样只隐藏超类的变量。您可以在构造函数中执行此操作 -

class Glob extends Monster
{
    public Glob() {
        health = 6;
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-18
    • 1970-01-01
    • 2018-05-06
    • 2010-10-10
    相关资源
    最近更新 更多