如何在 java 中创建对同一包中的其他 classes 不可见的(私有)class?

How to make a (private) class in java that is not visible to other classes in the same package?

我正在 Java 学习继承,我正在学习的那本书使用 Employee class 来解释几个概念。由于在同名 java 文件中只能有一个 (public) class,而这个 class 创建另一个 class 的对象,我有在同一个文件中定义一个 Employee class,没有 public 修饰符。我的印象是 classes 在同一 java 文件中的另一个 class 主体之后以这种方式定义 对其他 classes 不可见同一个包裹。这是用于演示的示例 Java 代码:

package book3_OOP;

public class TestEquality3 {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        Employeee emp1 = new Employeee("John", "Doe");
        Employeee emp2 = new Employeee("John", "Doe");

        if (emp1.equals(emp2))
                System.out.println("These employees are the same.");
        else
            System.out.println("Employees are different.");


    }

}

class Employeee {
    private String firstName, lastName;

    public Employeee(String firstName, String lastName) {

        this.firstName = firstName;
        this.lastName = lastName;

    }

    public String getFirstName() {
        return firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public boolean equals(Object obj) {

        //object must equal itself
        if (this == obj)
            return true;

        //no object equals null
        if (obj == null)
            return false;

        //test that object is of same type as this
        if(this.getClass() != obj.getClass())
            return false;

        //cast obj to employee then compare the fields
        Employeee emp = (Employeee) obj;
        return (this.firstName.equals (emp.getFirstName())) && (this.lastName.equals(emp.getLastName()));

    }
}

例如,class Employeee 对包 book3_OOP 中的所有 class 可见。这就是 Employee 中额外 'e' 背后的原因。到目前为止,我在这个包中有大约 6 个员工 class,例如 Employee5、Employee6 等等。

如何确保以这种方式在 .java 文件中定义的第二个 class 不会暴露给同一包中的其他 class?使用 privateprotected 等其他修饰符会引发错误。

使 Employee 成为静态 嵌套 classTestEquality3:

public class TestEquality3 {
    public static void main(String[] args) {
        Employee emp = new Employee("John", "Doe");
    }

    private static class Employee {
        private String firstName;
        private String lastName;

        public Employee(String firstName, String lastName) {
            this.firstName = firstName;
            this.lastName = lastName;
        }
    }
}

您也应该对其他 Employee class 执行此操作。如果与另一个 class 有任何冲突,您可以使用封闭的 class 名称来消除歧义:

TestEquality3.Employee emp = new TestEquality3.Employee("John", "Doe");