从超类(JAVA)访问私有变量 [英] Access a private variable from the superclass (JAVA)

查看:256
本文介绍了从超类(JAVA)访问私有变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,所以我学习了所有学期的java,并认为我对继承和超级/子类有一个清晰的认识。今天我们被赋予了一个叫做敌人的超级类别的任务,其中有不同类型的敌人。我做的一切都很好,我的所有子类都正常工作,但当我回去阅读我们必须遵循的指南时,我发现了这句话:

Ok so I have studied java all semester and thought I had a clear understanding about inheritance and super/sub classes. Today we were given as assignment for making a superclass called enemy, with sub classes of different types of enemies. I did everything fine and all of my subclasses are working, but when I went back to read the guidelines we must follow, I found this sentence:


超类的所有成员变量必须是私有的。对变量的任何访问都必须通过子类中的受保护方法来完成。

"All member variables of the super class must be private. Any access to a variable must be done through protected methods in the subclasses."

据我所知,这对我来说毫无意义。如果变量在超类中是私有的,那么即使从子类中也不允许访问?讨论子类中受保护方法的最后一部分对我来说也没有任何意义。这有什么帮助和/或允许对超类的任何访问?

From what I have learned, this makes no sense to me. If a variable is private within the superclass, doesn't that disallow access even from a subclass? The last part that talks about protected methods in the subclasses also doesn't make any sense to me. How does this help and/or allow any access whatsoever to the super class?

从我对继承的了解,以下是我认为是真的:

From what I've learned about inheritance, Below is what i thought was true:

                Access Levels
 Modifier    Class  Package Subclass    World
 public        Y      Y        Y        Y
 protected     Y      Y        Y        N
 no modifier   Y      Y        N        N
 private       Y      N        N        N

如果我在这里理解错误,请解释一下!我不想让教练给我们错误的指示,如果我不是正确理解它的话!

If I'm understanding something wrong here please do explain! I don't want to confront the instructor about giving us faulty instructions, if I'm the one not understanding it correctly!

推荐答案

部分

Any access to an a variable must be done through protected methods in the sub classes.

...只是意味着子类必须调用超类中定义的受保护方法。由于这些方法受到保护,因此子类可以访问它们。

... just means that the subclasses have to call protected methods that are defined in the superclass. Since these methods are protected they can be accessed by the subclasses.

首先,你要定义一个这样的基类:

First you would define a base class like this:

public class Base {

    private int x;  // field is private

    protected int getX() {  // define getter
        return x;
    }

    protected void setX(int x) {  // define setter
        this.x = x;
    }
}

然后你会在你的子类中使用它,就像这样:

Then you would use it in your child class like this:

class Child extends Base{

    void foo() {
        int x = getX(); // we can access the method since it is protected.
        setX(42);  // this works too.
    }
}

这篇关于从超类(JAVA)访问私有变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆