0

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

  1. name is protected in Person and emily is an employee which extends Person. So emily.name is legal; and
  2. Person is in the same package as Test. So we can access name in Test class.

Is my guess correct?

  • Yup, that's right. – Michael Bianconi Feb 12 '20 at 20:02
  • Right. You wouldn't be able to access salary, because that's outside the package. BTW, I had been programming in Java for a decade before I learned that protected made a member available to other classes in the same package. I had thought it was only child classes that it opened it up to. Pro tip: Never use such visibility tricks. – Zag Feb 12 '20 at 20:42

0 Answers0