Isn’t that subclass inherits everything from superclass true? But subclass could not access its superclass’s private attribute/method, but can access its own. So I wrote a test program. But it seems subclass has not one!
class a {
private void set() {
System.out.println("a.set()");
}
}
public class b extends a {
// private void set() {
// System.out.pritln("b.set()");
// }
void f() {
set();
}
public static void main(String[] args) {
b b = new b();
b.f();
}
}
If I comment out the set() method in b as the example does, it won’t compile.
Any idea? Any explanation from JVM view ?
Yes,
privatemethods aren’t accessible from a derived class.protectedandpublicare.When you declare
setin your derived class, you gain access to this derived version since it’s now part of the class (no longer aprivatebase class method).You’d still get an error if you attempted to call
super.set().Edit: the trick aroth’s talking about I assume is reflection. 🙂 Don’t.