[英]Is there any way to define a private class in Java which only other classes in the same package can access it?
[英]How to make a (private) class in java that is not visible to other classes in the same package?
我正在研究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()));
}
}
例如,包book3_OOP
中的所有類都可以看到Employeee
類。 這就是Employee中多余的“ e”的原因。 到目前為止,此程序包中大約有6個員工類,例如Employee5,Employee6等。
如何確保以這種方式在.java文件中定義的第二個類不會暴露給同一包中的其他類? 使用其他修飾符,例如private
或protected
拋出錯誤。
使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");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.