为什么我不能以这种方式访问​​ Java 中的受保护变量? [英] Why can't I access a protected variable in Java this way?

查看:38
本文介绍了为什么我不能以这种方式访问​​ Java 中的受保护变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样定义的类:

I've a class defined this way:

package prueba;

public class OtraClase {

[...]

protected int num3;

[...]

另一个类是这样定义的:

And another class defined this way:

package otro;

import prueba.*;

public class OtraClaseMas extends OtraClase{

但是如果在最后一个类中我创建了一个 OtraClase 对象,我就不能做这样的事情:

But if in that last class I create an OtraClase object I cannot do something like this:

createdObjectOfOtraClase.num3=1;

而且我认为根据文档我应该能够,这里.它说 protected 修饰符允许另一个包中它的类的子类访问.就我所见,我不认为它是另一个包中它的类的子类.

And I think that according to the documentation I should be able to, here. It says that the protected modifier allows for access by a subclass of its class in another package. And as much as I look at it I don't see it being another thing than exactly a subclass of its class in another package.

我是不是误解了什么?

我要么使用类的构造函数,要么在另一个不同的函数中使用,但在这两个地方都不起作用.

I'm either using the constructor of the class and in another different function and it doesn't work in neither place.

构造函数代码:

public OtraClaseMas(int num, int num2,int num3)
{
    super(num, num2,num3);      
    OtraClase oc=new OtraClase(1,1,1);
   //oc.num3=1; This doesn't work
}

方法代码:

public void foo()
{
    OtraClase oc=new OtraClase(1,1,1);
    //oc.num3=1; This doesn't work

}

推荐答案

protected 变量可以从同一个包或派生类访问它们自己的成员的方式访问,但如果您在超类的包之外创建了超类的实例,即使您扩展了同一个超类,您也无法访问它

A protected variable can be accessed from the same package or by the derived classes the same way they access their own members, but if you create an instance of the super class outside of the package of the superclass, you wont be able to access it even if you are extending this same superclass

package packageA;
public class ClassA {
    protected int variableA;
}

package packageA;
public class ClassC {
    public void setVariableA() {
        ClassA classA = new ClassA();
        classA.variableA = 1; // OK
    }
}

package packageB;
public class ClassB extends ClassA {
    public void setVariableA() {
        ClassA classA = new ClassA();
        variableA = 1; // OK
        classA.variableA = 1;// this wont work
    }
}

这篇关于为什么我不能以这种方式访问​​ Java 中的受保护变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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