Say I have a class with some members, and the members have a less restrictive access modifier than the class itself.
A concrete example could be:
package apples;
class A { // package private
public int foo() { // public (=> less restrictive than *package private*)
return 42;
}
}
To my understanding a class access modifier that is more restrictive than the member access modifier, will override the less restrictive member access modifiers. So a less restrictive member access modifier should have no effect at all.
- Is my understanding correct?
- If not, what are the consequences?
- What could be valid reasons to have less restrictive member access modifiers?
- Finally, what are there best practice to follow?
I also did some experimenting because I thought it might have consequences once I start passing function references around, however even then the access modifier does not seem to matter.
The situation that I constructed is the following:
apples.Bprovides a public methodbla()that returns a reference toapples.A.foo.- Then
pizzas.Ccallsapples.B.blato obtain a reference toA.fooand calls it. - So
A.foo()is not directly visible toC, but is only indirectly accessible viaB.bla()
I tested it and it does not make a difference whether I make the access modifier of foo() package private or not.
package apples;
import java.util.function.IntSupplier;
public class B {
public IntSupplier getReferenceToAFoo() {
A aInstance = new A();
return aInstance::foo;
}
}
package pizzas;
import apples.B;
import java.util.function.IntSupplier;
public class C {
private int callAFooIndirectly() {
B bInstance = new B();
IntSupplier intsupplier = bInstance.getReferenceToAFoo();
return intsupplier.getAsInt();
}
public static void main(String[] args) {
C cInstance = new C();
int i = cInstance.callAFooIndirectly();
System.out.println(i);
assert 42 == i;
}
}