简体   繁体   English

私有方法可以在 java 中的 class 之外访问

[英]private method can be accessed outside class in java

i have tried the following code in net beans i am expecting error but i didn't get any error我已经在 net beans 中尝试了以下代码我期待错误但我没有收到任何错误

class B {

    private void method() {
    }

    public static void main() {
        B b = new B();
        B c = new C();
        b.method();
        c.method();
    }
}

class C extends B {
}

When c.method() tries to access the method it should show error but in NetBeans it is not showing.c.method()尝试访问它应该显示错误的方法时,但在 NetBeans 中它没有显示。 Please tell me what is the fault.请告诉我是什么问题。

The way you have your method defined, you are calling C.method() from inside B.main() .您定义方法的方式是从 B.main() 内部调用C.method() B.main() Since method is private to B , the method is visible inside of B.main() even though the object is of type C which inherits from B .由于方法是B私有的,因此该方法在 B.main() 内部可见,即使 object 的类型是C ,它继承自B

The access checking is not done at object/class level, but rather at scope level.访问检查不在对象/类级别进行,而是在scope级别进行。 You call the method in B 's scope where it is accessible.您调用B的 scope 中的方法,它可以访问。 It doesn't matter whether you call it on a C object or a B object.无论您是在C object 还是B object 上调用它都没有关系。

That's because the main method is declared inside class B and has visibility to all B private methods.这是因为main方法是在 class B内部声明的,并且对所有B私有方法都具有可见性。

When doing c.method() , the IDE knows that C extends B and it knows that main is inside B so it can see the private method (with referring to B ).在执行c.method()时,IDE 知道C extends B并且它知道mainB内部,因此它可以看到B的私有方法。


That's the "register" you'll find on the compiled B class (from Eclipse).这就是您可以在编译后的B class(来自 Eclipse)上找到的“寄存器”。

public static void main(java.lang.String[] args);
    new com.example.B [1]
    dup
    invokespecial com.neurologic.example.B() [17]
    astore_1 [b]
    invokespecial com.example.C() [20]
    astore_2 [c]
    aload_1 [b]
    invokespecial com.example.B.method() : void [21]
    aload_2 [c]
    invokespecial com.example.B.method() : void [21]
    return

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

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