package p1;
public class Person {
protected String name;
}The following class in the same package can access the variable name directly:package p1;
public class Employer {
void hireEmployee() {
Person p = new Person();
p.name = "Nam"; // access protected variable directly
}
} The following class is in different package but it extends the Person class so it can access the variable name directly:package p2;
import p1.Person;
class Employee extends Person {
void doStuff() {
name = "Bob";
}
}But the following class, in different package, cannot access the variable name directly:package p2;
import p1.Person;
class AnotherEmployer {
void hire() {
Person p = new Person();
// compile error, cannot acceess protected variable
// from different package
p.name = "Nam";
}
}Related keyword: public and private. See all keywords in Java.
Nam Ha Minh is certified Java programmer (SCJP and SCWCD). He began programming with Java back in the days of Java 1.4 and has been passionate about it ever since. You can connect with him on Facebook and watch his Java videos on YouTube.