繁体   English   中英

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

[英]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文件中定义的第二个类不会暴露给同一包中的其他类? 使用其他修饰符,例如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");

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM