Java 访问修饰符:从另一个包访问默认值 class

Java Access Modifiers: Accessing default class from another packages

如何使用 public class 包中的 class 访问 some/another 包中的默认设置。

例如,

我的 Bank package 有 2 class 个

  1. public class Bank { ... }

  2. class Account { ... }(默认访问修饰符)

我需要使用 Bank 在另一个名为 Atmpackage 中访问 Account

有什么建议吗?

根据 java 的 Accessing class/method/instances 规则,

the default things(class/method/instances) must not be visible into another package.

So, here in your case it's not possible to access it through another package because default class not visible to there.

default things visible within same package only where it's define/declare

您无法直接从另一个包访问此 class,但您可以使用 proxy pattern 并通过调用银行方法来调用帐户方法

根据定义,java 中 classes 的默认访问修饰符只能从其包内访问(参见 here)。

如果您有权访问源代码,您应该考虑将访问级别更改为 public。否则,您可以尝试通过同一包中的 public class 访问 class。

package test.bankaccount;
public class Bank {
    public Account getAccount(int id) {
        //here goes the code to retrieve the desired account
    }
}

package test.bankaccount;
class Account {
    // class implementation
}

无论如何,您应该记住,访问限制总是描述应用程序的工作方式。您应该问自己为什么特定的 class 不是 public.

如果 classes 是您自己的代码,那么问问自己您设置的访问限制是否正确地代表了您希望应用程序工作的方式。