class A{
private void sayA(){
System.out.println(\"Private method of A\");
}
public static void main(String args[]){
A instanceA=new B();
ins
Accessibility is a compile time concept (reflected in Reflection APIs).
From the Java Language Specification
Note that accessibility is a static property that can be determined at compile time; it depends only on types and declaration modifiers.
That is, the compiler doesn't care what the runtime type of the instance referenced by your variable named instanceA
will be
A instanceA = new B();
It only cares that you invoked a method on a reference of static type A
. That method is private
and since you are within the body of the class which declares it, it is visible, and therefore usable.
Otherwise, the member or constructor is declared private, and access is permitted if and only if it occurs within the body of the top level class (§7.6) that encloses the declaration of the member or constructor.
For spiderman in comments, consider the following
class A {
private void privateMethod () {
System.out.println("private method");
}
public void publicMethod() {
privateMethod();
}
}
class B extends A {}
class Example {
public static void main(String[] args) {
new B().publicMethod();
}
}