SCJP note #1: On accessing protected members

To remind myself of important very important things I shouldn’t overlook in taking the SCJP exam, I shall (intermittently) post notes about it.

On accessing a protected member from a class of a different package (say Class1), even if another class (Class2) subclassed Class1, it still cannot use a reference to Class1 to access its protected member.

From Java 2:
1. package testpkg.p1;
2. public class ParentUtil {
3. public int x = 420;
4. protected int doStuff() { return x; }
5. }
1. package testpkg.p2;
2. import testpkg.p1.ParentUtil;
3. public class ChildUtil extends ParentUtil {
4. public static void main(String [] args) {
5. new ChildUtil().callStuff();
6. }
7. void callStuff() {
8. System.out.print(”this ” + this.doStuff() );
9. ParentUtil p = new ParentUtil();
10. System.out.print(” parent ” + p.doStuff() );
11. }
12. }

In the preceding code, line 10 will create a compiler error. Why? Because ChildUtil is accessing ParentUtil’s protected member. Even if ChildUtil is a child of ParentUtil, it is still treated as a class outside the package where the latter belongs. In order to access the ParentUtil’s protected member, see line 8. ChildUtil is a subclass of ParentUtil thus, it inherited the doStuff() method. As far as I’ve learned that’s the legal way of accessing it.

Leave a Reply