繁体   English   中英

如何在子类中访问超类的“protected static”变量,其中子类位于不同的包中..?

[英]How can ‘protected static’ variable of superclass be accessed in the subclass, where subclass resides in different package..?

这是同一个问题的略微详细版本。

我们无法访问子类中受保护的变量(超类),其中子类位于不同的包中。我们只能访问supeclass的继承变量。 但是如果我们将修饰符更改为'protected static',那么我们也可以访问超类的变量。 为什么会那样。?

这是我试图解释的代码片段。

package firstOne;

public class First {
    **protected** int a=7;
}

package secondOne;

import firstOne.*;

public class Second extends First {
    protected int a=10; // Here i am overriding the protected instance variable

    public static void main (String [] args){
        Second SecondObj = new Second();
        SecondObj.testit();
    }
    public void testit(){
        System.out.println("value of A in Second class is " + a);
        First b = new First();
        System.out.println("value in the First class" + b.a ); // Here compiler throws an error.
    }
}

上述行为是预期的。 但我的问题是,如果我们将超类实例变量'a'的访问修饰符更改为'protected static',那么我们也可以访问变量(超类的变量)。 我的意思是,

package firstOne;

public class First {
    **protected static** int a=7;
}

package secondOne;

import firstOne.*;

public class Second extends First {
    protected int a=10;

    public static void main (String [] args){
        System.out.println("value in the super class" + First.a ); //Here the protected variable of the super class can be accessed..! My question is how and why..?
        Second secondObj = new Second();
        secondObj.testit();
    }

    public void testit(){
        System.out.println("value of a in Second class is " + a);
    }

}

上面的代码显示了输出:

超级7中的价值

test1类中x的值为10

这怎么可能...?

从“检查Java虚拟机中受保护成员的访问权限”:

m是属于包p的类c中声明的成员。 如果m是public,则可以通过(code in)任何类访问它。 如果m是私有的,则只能通过c访问。 如果m具有默认访问权限,则只能由属于p的任何类访问它。

如果m受到保护,事情会稍微复杂一些。 首先, m可以被属于p的任何类访问,就像它具有默认访问权一样。 此外,它可以被C属于与p不同的封装的任何亚类s中被访问,但有下列限制:·如果m不是静态的,则类ø其成员正在被访问必须是S或A的对象的S的子类中,书面ö≤ (如果m是静态的,则限制不适: 可被S总是访问)。

我在JLS第6.6.2.1节中找到了引用,它支持关于“正在访问其成员的对象必须是s或子类......”的部分。 我没有看到任何支持静态子句的东西,但根据你自己的例子,它显然是正确的。

覆盖仅适用于方法,而不适用于类变量。 没有覆盖变量的东西。 您正在隐藏访问超类变量a的符号。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM