Say I have this abstract class:
package test.one;
public abstract class One {
protected abstract void whatever();
public void run() {
whatever();
}
}
And use it like this:
package test.two;
import test.one.One;
public class Three {
public static void main(String[] args) {
One one = new One() {
@Override
protected void whatever() {
System.out.println("Do whatever..");
}
};
one.whatever();
}
}
This code fails on compilation which is pretty much expected.
test/two/Three.java:14: error: whatever() has protected access in One
one.whatever();
^
1 error
But the below code compiles successfully which seems surprisingly:
package test.two;
import test.one.One;
public class Two {
public static void main(String[] args) {
new One() {
@Override
protected void whatever() {
System.out.println("Do whatever..");
}
}.whatever();
}
}
The difference is that in the latter case I'm accessing the method without a named reference. Why does the compiler allow such access?