与类访问修饰符相比,限制较少的成员访问修饰符有什么用?

Ste*_* D. 8 java oop access-modifiers

假设我有一个带有一些成员的类,并且这些成员的限制访问修饰符比类本身少。

一个具体的例子可能是:

package apples;

class A { // package private
    public int foo() { // public (=> less restrictive than *package private*)
        return 42;
    }
}
Run Code Online (Sandbox Code Playgroud)

据我所知,一个类访问修饰符的限制要比成员访问修饰符的限制更大,它将覆盖限制性较小的成员访问修饰符。因此,限制较少的成员访问修饰符应该完全无效。

  • 我的理解正确吗?
    • 如果没有,后果是什么?
  • 限制成员访问修饰符较少的正当理由是什么?
  • 最后,有什么最佳实践可遵循?

我也做了一些试验,因为我认为一旦开始传递函数引用,它可能会产生后果,但是即使那样,访问修饰符似乎也没有关系。

我构造的情况如下:

  • apples.B提供bla()返回对的引用的公共方法apples.A.foo。
  • 然后pizzas.C调用apples.B.bla获取A.foo对它的引用并对其进行调用。
  • 因此对A.foo()不能直接看到C,而只能通过间接访问B.bla()

我已经对其进行了测试,并且无论是否将foo() 包的访问修饰符设为私有,这都没有什么不同。

package apples;

import java.util.function.IntSupplier;

public class B {
    public IntSupplier getReferenceToAFoo() {
        A aInstance = new A();
        return aInstance::foo;
    }
}
Run Code Online (Sandbox Code Playgroud)
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;
    }
}

Run Code Online (Sandbox Code Playgroud)

T.J*_*der 8

我的理解正确吗?

是。

限制成员访问修饰符较少的正当理由是什么?

两个原因:

  • Sometimes, you're implementing an interface; interface methods must be public
  • It makes it easier to change the overall access of your class. For instance, if you mark all the methods that you'd ever want to be public public, even in a package-private class, then later all you have to do to make the class public is add public to the class declaration.

Finally, what are there best practice to follow?

That's a matter of opinion, so not well-suited to a Stack Overflow question or answer. Do what seems reasonable to you and/or your team, and/or do what your team's style guide tells you to do.