I have 3 classes, class Person in package A, class Employee extends Person in package B, and class Test in package A:
In Person.java:
package A;
public class Person {
protected String name;
...
}
In Employee.java:
package B;
import A.Person;
public class Employee extends Person {
double salary;
...
}
In Test.java:
package A;
import B.Employee;
import java.util.*;
public class Test {
public static void main(String[] args) {
Employee emily = new Employee("Emily", 20000.0);
System.out.println(emily.name);
}
}
My question is regarding the println statement. Initially, I though it is illegal because Test is in a different package than Employee and Test does not extend Employee. Since name is protected, it can only be accessed from the same package or in a subclass.
However, I compiled and ran the code. The println statement is legal. My guess is that it is legal because
- name is protected in Person and emily is an employee which extends Person. So emily.name is legal; and
- Person is in the same package as Test. So we can access name in Test class.
Is my guess correct?