我正在学习Java中的继承,而我正在研究的书使用Employee
类来解释几个概念。由于在同一个java文件中只能有一个(公共)类,并且这个类创建了另一个类的对象,我必须在同一个文件中定义一个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
中的所有类都可见。这是员工中额外“e”背后的原因。截至目前,我在此软件包中有大约6个员工类,例如Employee5,Employee6等。
如何确保.java文件中以这种方式定义的第二个类不会暴露给同一个包中的其他类?使用其他修饰符(如private
或protected
会抛出错误。
答案 0 :(得分:4)
让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");