The compiler is capable of telling you that your attempt to access a private variable outside of the declaring class is invalid. You don’t have to go through the runtime to get that.
As an addendum: the code isn’t semantically valid, per the JLS:
- A member (class, interface, field, or method) of a reference type, or a constructor of a class type, is accessible only if the type is accessible and the member or constructor is declared to permit access:
- […] 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.
If you want access to it, traditionally you use a getter for it…
public int getA() {
return a;
}
…but if you don’t want to make another method (for whatever reason), change its visibility to public
instead.
3
solved Why would this give a compile time error and not runtime error?