private method can be accessed outside class in java
i have tried the following code in net beans i am expecting error but i did开发者_运维技巧n't get any error
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. Please tell me what is the fault.
The way you have your method defined, you are calling C.method()
from inside 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
.
The access checking is not done at object/class level, but rather at scope level. You call the method in B
's scope where it is accessible. It doesn't matter whether you call it on a C
object or a B
object.
That's because the main
method is declared inside class B
and has visibility to all B
private methods.
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
).
That's the "register" you'll find on the compiled B
class (from 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
精彩评论