gpt4 book ai didi

java - 如何在 java 中创建一个对同一包中的其他类不可见的(私有(private))类?

转载 作者:行者123 更新时间:2023-11-30 07:02:10 25 4
gpt4 key购买 nike

我正在学习 Java 中的继承,我正在学习的书使用 Employee 类来解释几个概念。由于同名的 java 文件中只能有一个(公共(public))类,并且该类创建另一个类的对象,因此我必须在同一个文件中定义一个 Employee 类,而不是 public修饰符。我的印象是,在同一 java 文件中的另一个类主体之后以这种方式定义的类对同一包中的其他类不可见。下面是用于演示的示例 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()));

}
}

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

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

最佳答案

使 Employee 成为 TestEquality3 的静态嵌套类:

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 类执行此操作。如果与另一个类有任何冲突,您可以使用封闭的类名来消除歧义:

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

关于java - 如何在 java 中创建一个对同一包中的其他类不可见的(私有(private))类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29325031/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com