samedi 28 mars 2015

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



I'm studying inheritance in Java and the book I'm studying from uses an Employee class to explain several concepts. Since there can be only one (public) class in a java file of the same name, and this class creates objects of another class, I have to define an Employee class in the same file, without the public modifier. I was under the impression that classes defined this way after another class body in the same java file aren't visible to other classes in the same package. Here's a sample Java code for demonstration:



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()));

}
}


For instance, the class Employeee is visible to all classes in the package book3_OOP. Which is the reason behind the extra 'e' in Employee. As of now I have about 6 employee classes in this package, such as Employee5, Employee6, and so on.


How do I ensure that the second class defined in this way in a .java file aren't exposed to other classes in the same package? Using other modifiers like private or protected throw errors.




Aucun commentaire:

Enregistrer un commentaire