0

In Java, how can I access protected members in a different package?

package p1
    class base      
        protected int x

package p2
    import p1.*
    class derived extends base
        int x

class subderived extends derived
     int x

From subderived main I want to access x of p1.base as protected specification we can use only inheritance we can't use reference to access base x. To access derived x we can use super.x, but from subderived, how can we access base.x?

wchargin
  • 15,589
  • 12
  • 71
  • 110

1 Answers1

2

Protected members are accessible from immediately derived and sub-derived classes without any qualifiers: rather than writing

base.x = 123;

you can write

x = 123;

and it will compile fine, as long as it is in a method of a derived class. However, in order for this to work, you need to remove members with the same name from the derived class itself: otherwise, the base member is hidden, and cannot be accessed through more than one level of inheritance hierarchy through the normal syntax of the language, i.e. without using reflection.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • 1
    but isn't `derived.x` [hiding](http://docs.oracle.com/javase/tutorial/java/IandI/hidevariables.html) `base.x`? – wchargin Mar 24 '13 at 20:01
  • @WChargin You are correct, I missed the fact that there's `x` in the derived class hiding the `x` in the base. I doubt that that other `x` is put there intentionally, so I updated the answer to reflect this. Thanks! – Sergey Kalinichenko Mar 24 '13 at 20:12